Create json object in php foreach loop - parsing

I have the following in php:
$follow=explode(" ",$_SESSION['Following']); //create array from the string stored in session variable
foreach($follow as $val) {
$show = $val;
//my query
$result=mysqli_query($dbc,$query);
WHILE ($rows = mysqli_fetch_assoc($result)) {
//$array[]= $rows; // tried this
//$array=json_encode($rows); //tried this
//array_push($array,$rows); // tried this
}
$json_array=json_encode($array);
echo $json_array;
If I take a single pass through the foreach loop the json object looks like this:
[{key:value}....], which can be parsed in my javascript.
However, with multiple passes in the foreach I am getting multiple arrays
within the object ,like this: [{key:value}][{key:value}]..... which results in the following
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data, which I guess are the []'s inside the object. How can I create the json object in the foreach loop to fix this?

Fixed it. I was echoing $json_array inside the foreach loop.

Related

Foreach controller not working for Json data

I have below json
[
{
"id": 13059,
"xid": "81f4278a53fe4c1a8d03346a34d76a47",
"yid": "8cbefbadec52ced5:e4f6801:17c73aeaf21:-5a75"
},
{
"id": 13059,
"xid": "061ef5792e8f4603bb1f86c71e6fb16c",
"yid": "8cbefbadec52ced5:e4f6801:17c73aeaf21:-5a56"
},
{
"id": 13061,
"xid": "4290987b25b34ffbb5b0329f1ab1b673",
"yid": "8cbefbadec52ced5:e4f6801:17c73aeaf21:-5dd4"
},
{
"id": 13063,
"xid": "57c4a2790aa44376be1e5215c5cb7ad0",
"yid": "8cbefbadec52ced5:e4f6801:17c73aeaf21:-585e"
}
]
Now I put the above json in global variable in JSR223 sampler
vars.put("jsonVariable",JSON.stringify(aboveJson))
Now next I add "ForEach Controller" and add
InputVariable Prefix = jsonVariable
Output variable name = outVariable
Then I add another JSR223 sampler inside ForEach Controller and log below data
log.info(${outVariable})
But ForEach controller is not even executing for once. Please let me know where I did wrong
ForEach Controller isn't smart enough to parse your JSON structure, it iterates an individual set of JMeter Variables which looks like:
var_1=foo
var_2=bar
etc.
so depending on what you're trying to achieve you need to:
In case if you want individual values of id, xid and/or yid - add 1 or more JSON Extractors and configure them to fetch the values from the response. Then use ForEach Controller and feed the variable from JSON Extractor to it
If you want to iterate JSON Objects instead you can use JSR223 PostProcessor and the following Groovy code:
new groovy.json.JsonSlurper().parse(prev.getResponseData()).eachWithIndex { entry, int index ->
vars.put('json_' + (index + 1), new groovy.json.JsonBuilder(entry).toString())
}

PHPExcel str_replace

i want to convert my excel hyperlink's path to open links with PHPExcel.
$links = $objPHPExcel->getActiveSheet()->getHyperlinkCollection();
This method will return an array of hyperlink objects, indexed by cell address; and you could then use array_filter() with an appropriate callback and the ARRAY_FILTER_USE_KEY flag set to extract those within a specific range.
my var_dump($links); output :
But i dont know how to loop the array of objects with array_filter() function..
I try :
$test = str_replace($links, "file", "mnt");
var_dump($test);
and i got the error above.. Any ideas please ?
The collection is an array of objects, indexed by cell address; and the PHPExcel_Cell_Hyperlink object has a set of documented methods for accessing and setting its data:
foreach($links as $cellAddress => $link) {
// get the URL from the PHPExcel_Cell_Hyperlink object
$url = $link->getUrl();
// change the URL however you want here
$url = str_replace($url, "file", "mnt");
// Set the new value for the link
$link->setUrl($url);
}
If you want to modify just those URLs for cells in column N, then you can wrap them in an if test:
foreach($links as $cellAddress => $link) {
// Test for column N
sscanf($cellAddress, '%[A-Z]%d', $column, $row);
if ($column == 'N') {
// get the URL from the PHPExcel_Cell_Hyperlink object
$url = $link->getUrl();
// change the URL however you want here
$url = str_replace($url, "file", "mnt");
// Set the new value for the link
$link->setUrl($url);
}
}

ZF2 : Change a row field in ResultSet

I want to change a row field in my ResultSet before returning it to my Controller.
$resultSet->buffer();
foreach ($resultSet as $row) {
$row->foo = $newvalue;
}
return $resultSet;
Problem is, when I use the buffer() function I can indeed loop over my ResultSet and make some changes on my rows, but once the loop ends all changes are gone.
I tried to set up a reference on $row :
foreach ($resultSet as &$row)
But then caught the following exception :
Fatal error: An iterator cannot be used with foreach by reference
I also tried to change resultSet to array but the same problem occurs.
Have I missed something ?
I don't think it is possible via the usual ResultSet usage. The array solution might work only if you are going to use the array in loops (foreach() in this case).
From any Table class -
$arr_resultSet = array();
foreach ($resultSet as $row) {
$row->foo = $newvalue;
//Object is assigned instead of converting it to an array.
$arr_resultSet[] = $row;
}
return $arr_resultSet;
Usage of this array in controller or view file -
//Here you can access that $row object as if the $resultSet was never converted to array.
foreach($arr_resultSet as $row) {
echo $row->foo;
}
No need of buffer(). I hope it works for now. Will definitely search for a proper solution.

Cannot query a second result set without looping through the first result set

I am having an issue with ZF2 trying to use the table gateways and getting result sets:
I am trying to query two result sets (from two different tables/two different gateways) and send them to the view to be iterated through and placed on the screen.
(Simplified example):
function viewAction() {
$table1 = $this->getServiceLocator()->get('Model\Table\Table1');
$table2 = $this->getServiceLocator()->get('Model\Table\Table2');
return new ViewModel([
'table1' => $table1->fetchAll(),
'table2' => $table2->fetchAll()
]);
}
With the Model\Table\Table1 and Model\Table\Table2 having a fetch all:
public function fetchAll() {
return $this->tableGateway->select();
}
Then in my view:
...
<?php
foreach($table1 as $row) {
echo "<tr><td>{$row['col1']}</td><td>{$row['col2']}</td></tr>";
}
?>
...
<?php
foreach($table2 as $row) {
echo "<tr><td>{$row['col1']}</td><td>{$row['col2']}</td></tr>";
}
?>
...
The problem is, $table1 will have no data when looping. However, if I instead do something like this (in the controller, instead of passing the result set to the view, passing $results1 and $results2 to the view):
$fetchAll = $table1->fetchAll();
$results1 = [];
foreach($fetchAll as $row) {
$results1[] = $row;
}
$fetchAll = $table2->fetchAll();
$results2 = [];
foreach($fetchAll as $row) {
$results2[] = $row;
}
Then all works fine. I don't want to have to loop through the same set of data twice. So why does ZF2 prevent me from using two different ResultSets before all the data in a ResultSet has been accessed?
Since I was querying to different record sets one after the other, the database was still waiting for action to take place on the first query. I could only have one action record set at a time.
There first solution was what I presented in the question, get a record set and loop through all the rows that are available before trying to query again. This frees the record set as we have all the data.
The second solution (the one I have adapted), is to enable Multiple Active Record Sets (MARS) for the database connection.
I was able to do this by adding MARS_Connection=yes to the dsn connection string for MSSQL.

JSON made with .to_json (of a collection) in Rails model not readable jquery

I fetched the results of a query in the model. Next i right away added a .to_json and assumed I will get a correct JSON object. But JQuery was not able to parse the json
def self.get_all_specials(year)
data_array=AttributeCalendarAnnual.find(:all, :conditions=>["created_at between ? and ?",Date.civil(Date.today.year), Date.civil(Date.today.next_year.year)], :order=>["created_at asc"])
return data_array.to_json
end
But the result I get is not a valid JSON it seems.
EDIT
The output :
[{"created_at":"2012-01-17T17:38:27Z","id":1,"in_market_end_date":"2012-01-31T23:59:59Z","in_market_start_date":"2012-01-18T00:00:00Z","initiative_id":1,"is_mail_count_selected":true,"is_mailer_selected":true,"is_market_selected":true,"is_offer_selected":true,"mail_count":1,"mailer_start_date":"2012-01-25T00:00:00Z","offer_selection_end_date":"2012-01-12T23:59:59Z","offer_selection_start_date":"2012-01-09T00:00:00Z","updated_at":"2012-01-17T17:38:27Z"},{"created_at":"2012-01-17T20:21:37Z","id":2,"in_market_end_date":"2012-01-28T23:59:59Z","in_market_start_date":"2012-01-24T00:00:00Z","initiative_id":3,"is_mail_count_selected":true,"is_mailer_selected":true,"is_market_selected":true,"is_offer_selected":true,"mail_count":5,"mailer_start_date":"2012-01-30T00:00:00Z","offer_selection_end_date":"2012-01-21T23:59:59Z","offer_selection_start_date":"2012-01-09T00:00:00Z","updated_at":"2012-01-17T20:21:37Z"}]
if you are simply outputting the escaped object to your page and hoping JS will parse it this will not work because it will be interpreted as a string. Instead try feeding the string into a function like this:
function parseJSON(txt, escape) {
if (escape === true) {
txt = unescape(txt);
}
return new Function("return " + txt)();
}
var result = parseJSON(someString);

Resources