php encode nested json in wrong format - php

I trying to test display a nested Json structure but the result is in wrong format.
php
while($row=$statement->fetch()){
$value=str_replace('"','',$row['item_option_value']);
$option[$row['item_option_name']]=explode(',',$value);
$all[$row['oid']]=$option;
}
echo json_encode($all);
mysql databas structure
Here is the result when i run the script.
I want the json structure to be the right side of the screenshot. Anyone knows what's wrong?

You would need to empty the $option arrays then like this:
$option = []; //or $option = array(); in PHP < 5.4
This is needed in order not to keep storing the data from the previous iteration.
So:
while($row=$statement->fetch()){
$value=str_replace('"','',$row['item_option_value']);
$option = [];
$option[$row['item_option_name']]=explode(',',$value);
$all[$row['oid']]=$option;
}
echo json_encode($all);

The problem is because of this line here,
$option[$row['item_option_name']]=explode(',',$value);
In each iteration of while() loop, you're appending the previously calculated $options array to $all. Instead, create an temporary array to hold intermediate result and append that to $all in each iteration, like this:
while($row=$statement->fetch()){
$opArray = array();
$value=str_replace('"','',$row['item_option_value']);
$opArray[$row['item_option_name']]=explode(',',$value);
$all[$row['oid']]=$opArray;
}
echo json_encode($all);

Related

I want a query result using codeigniter

i have an array result. i want to print 2 rows(product data) in first page.
next 2 rows in second page and so on. if anybody knows this,please help me to solve it
my array
$data['product_list']
foreach($data['product_list'] as $dat)
{
echo $dat->prd_id;
echo $dat->prd_name;
}
You are doing a foreach loop on an associative array and then trying to access the the contents as objects by using ->. I can only given assumption of what you might be doing. If your array is already populated with a name and id like you have described in your foreach loop this is how you would access the contents in the loop:
foreach($data['product_list'] as $dat)
{
echo $dat['prd_id'];
echo $dat['prd_name'];
}
That is how you would print out the contents providing you had the data stored in your array like so:
$data['product_list'][0] = array('prd_id'=>'id0','prd_name'=>'name0');
$data['product_list'][1] = array('prd_id'=>'id1','prd_name'=>'name1');
$data['product_list'][2] = array('prd_id'=>'id2','prd_name'=>'name2');
Better you try with array_slice();
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>

Encoding a single key in associative array to base64

I am trying to retrieve user data from a SQL table where one of the columns is blob_medium. I run the SQL query properly and get the data in the php script.
if(mysqli_num_rows($result)){
while($row=mysqli_fetch_assoc($result)){
$result_array['user_data'][]=$row;
}
}
Now, to json_encode this data, I need to encode the data of user_pic column to base 64. For that I am trying this. But, it seems I am doing something wrong. Any kind of help would be appreciated.
foreach($result_array as $key){
foreach($key as $key2){
//print_r(base64_encode($key2['user_pic']).'<br/>'.'<br/>');
$key2['user_pic'] = base64_encode($key['user_pic']);
//print_r(($key['user_pic']).'<br/>'.'<br/>');
}
}
When I uncomment the print_r statements my data is printed in base64 format but the data of the assoc array is not changing.
That's because the array's $key and $keys in the for loop are copies. If you want them to modify the original you can either do it by specifying them to be references, not copies:
foreach($result_array['user_data'] as &$key){
$key['user_pic'] = base64_encode($key['user_pic']);
}
Or by explicit index into the original:
foreach($result_array['user_data'] as $index => $key){
$result_array['user_data'][$index] ['user_pic'] = base64_encode($key['user_pic']);
}
That's because you're changing the $key2 array. A temporary value created by your foreachloop. I myself would recommend using a for loop in this specific situation, because I was told to never use a loop within a loop if I can prevent it, and it makes things a lot easier to read:
for($i=0; $i < count($result_array['user_data']); $i++){
$encodedUserPic = base64_encode($result_array['user_data'][$i]['user_pic']);
$result_array['user_data'][$i]['user_pic'] = $encodedUserPic;
}

PHP: String in json parse

I am trying to parse a json. I am running this in a foreach loop and if I do the following it works:
$places = array('restaurant', 'store', 'etc')
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
However, when I do the following, i.e. I change restaurant to $places (I need to do this since I have an array of different places and I want to parse all of them in a foreach loop) it doesn't work.
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}
Solution is changing $places to {$places}[0]
The $places array contains keywords, such as restaurant or store. So the [0] is referring to the first one in the json which is why it's needed.
Why do you have this in the first loop:
json[0]->restaurant[0]
json[0]->$restaurant[0]
But then in the next you have:
json[0]->$places[0]
json[0]->$places[0]
Perhaps you are parsing the JSON incorrectly and it should be:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}
And then in the first loop, you should do a similar edit to get rid of $restaurant[0]:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
Then again, unclear on what value $places has when you loop via foreach ($this->placesCachingTypes as $places) {. It does’t make sense what you would be looping through with the value of $places. And perhaps assigning that $places in the loop object of $json_decoded->json[0]-> is the source of your issues? Need more info from you to confirm this.

Returning an array of objects in a php function

I have multiple rows getting returned from a database query.
I am able to get just a row at a time, but I want to put the rows in an array of objects like this:
$trailheads[] = new StdClass;
Loop
{
$trailheads[] = $trailhead; // Put each object into the array of objects
}
But when I try to loop through each array, I am having trouble extracting the values of each row. What is the right way to loop through the returned object and get the values?
The code that does not work is pretty basic:
$returned_obj->o->trailhead_name
But I am actually hoping be able to loop through each array element.
Maybe try casting to array in your for loop, this is untested and may not work as is but should get you on the right track:
foreach ($trailheads as (array) $key){
// $key is now an array, recast to obj if you want
$objkey = (object) $key;
}
i'm assuming your using mysql since you did not say...
you can use thsi function mysql_fetch_object()
<?php
$trailheads = array()
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result, 'trailhead')) {
$trailheads[] = $row;
}

MySQL hierarchy data to JSON string in PHP

I have data in a MYSQL DB that looks like this:
id,parentid,name,count
1,0,top,10
2,1,middle1,5
3,1,middle2,5
4,3,bottom1,3
5,3,bottom2,2
and want to output it via PHP as a heirarchical JSON string where 'top' has a collection of 'middle's etc.
Get my drift? Anyone have a recursive PHP function to help?
if you've got your data in a PHP array/associative array, then you can use PHP 5.2's JSON functions:
http://www.php.net/manual/en/function.json-encode.php
keep reading on that page to the comments area, they practically give away the code without the fun of figuring it out yourself.
You can use the function here http://tagarga.com/blok/on/061029 to convert your adjacency list to a nested array, then json_encode() it.
function adj_tree(&$tree, $item) {
$i = $item['id'];
$p = $item['parentid'];
$tree[$i] = isset($tree[$i]) ? $item + $tree[$i] : $item;
$tree[$p]['_children'][] = &$tree[$i];
}
$tree = array();
$rs = my_query("SELECT * FROM categories");
while($row = my_fetch($rs))
adj_tree($tree, $row);
echo json_encode($tree[0]);

Categories