MySQL hierarchy data to JSON string in PHP - 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]);

Related

php encode nested json in wrong format

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);

Converting XML file elements into a PHP array

I'm trying to convert a Steam group members list XML file into an array by using Php.
The XML file is: http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml
The elements are the member's steam IDs, such as 76561198000264284
How can I go about doing this?
Edit: So far I've used something like this:
$array = json_decode(json_encode((array)simplexml_load_string($xml)),1);
It outputs the first few elements, not ones specifically
from
This should return the fully accessible array:
$get = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($get);
print_r($arr);
You can now access items like this:
echo $arr->groupID64;
echo $arr->members->steamID64;
Edit:
To parse the streamID, you can do a for loop
$ids = $arr->members->steamID64;
foreach($ids as $id) {
echo $id;
}
you can use below functional code to get your correct answer
<?php
$getfile = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($getfile);
foreach($arr->members->steamID64 as $a => $b) {
echo "<br>".$a,'="',$b,"\"\n";
}
?>
OUTPUT
steamID64="76561198009904532"
steamID64="76561198004808757"
steamID64="76561198000264284"
steamID64="76561198016710420"
steamID64="76561198005429187"
steamID64="76561198030184436"
steamID64="76561197980763372"
steamID64="76561197972363016"
steamID64="76561198045469666"
steamID64="76561198010892015"
steamID64="76561198028438913"
steamID64="76561197967117636"
steamID64="76561197980283206"
steamID64="76561197992198727"
steamID64="76561198018960482"
steamID64="76561198071675315"
steamID64="76561198010447988"
steamID64="76561198025628761"
if you wish to customize you can make it as per your need. let me know if i can help you more..

for loop and appending to an array in PHP

I have the following code:
$items = array();
foreach($following as $storeOwner)
{
array_push($items, $productRepository->mostRecentItem($storeOwner->getId(), 5));
}
I am trying to append the results of
$productRepository->mostRecentItem($storeOwner->getId(), 5)
to $items. How do I do so? Why doesn't the above code work?
Try this:
$items = array();
foreach($following as $storeOwner)
{
$items[] = $productRepository->mostRecentItem($storeOwner->getId(), 5);
}
Also, take a look to the result of the mostRecentItem Method... .
var_dump you different objects and return values to make sure that contain what you think they should contain. The code looks "correct" so it's probably the objects and values that are not.

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;
}

forcing json_encode to encode (sparse) array as indexed array in php

I am trying to transfer an array between the host and my webpage using JSON. On the host, I have a php script which reads a number of rows from a mysql table and creates an array out of it.
$query="select ID,val,size from db;";
$result=mysql_query($query);
while ($row=mysql_fetch_assoc($result)) {
$idx= (int) $row['ID'];
$data[$idx]['val']=$row['val'];
$data[$idx]['size']=$row['size'];
}
echo json_encode($data);
Normally, the ID's are incremented linearly between, for example, 0 and 99.. In this case, the json_encoded output is an array (and will be interpreted as an array in javascript... If I do an array.length, I get 100 as the answer)....
Sometimes, a few of the rows are missing from the table (maybe there was no row with an idx=40)... In this case, the array is json_encoded as a collection of objects. In javascript, if I try to look at array.length, I get an undefined result. I'd like to force the data array to be interpreted as an indexed array with null/0 values for missing rows. Is there an easy way to do this? It looks like the json_encode function has an option to force encoding as an associative array, but not the other way around.
Thx.
$query="select ID,val,size from db;";
$result=mysql_query($query);
$maxId = -1;
$defaultValue = null;
while ($row=mysql_fetch_assoc($result)) {
$idx= (int) $row['ID'];
if($maxId < $idx)
$maxId = $idx;
$data[$idx]['val']=$row['val'];
$data[$idx]['size']=$row['size'];
}
for($i=0;$i<$maxId;$i++)
if(!isset($data[$i))
$data[$i] = $defaultValue;
echo json_encode($data);
I would define $data as a full array and then replace elements inside of it.
$data = array_fill($starting_index, 100, null);
$query="select ID,val,size from db;";
$result=mysql_query($query);
while ($row=mysql_fetch_assoc($result)) {
$idx= (int) $row['ID'];
$data[$idx]['val']=$row['val'];
$data[$idx]['size']=$row['size'];
}
echo json_encode($data);
It's annoying, but that's Javascript for you. I usually work around this by adding another level to my data structure:
$data['size'] = count($myarray);
$data['array'] = $myarray;
echo json_encode($data);
That way you get the length included for "free", without having to do any client-side looping/counting.

Categories