简体   繁体   中英

Converting data returned from mysql query to json(tree based)

This question has been asked earlier too, but no body has answered I guess.

Lets say mysql query returns result like following

name    |  id
tarun   |   1
tarun   |   2
tarun   |   3 

Now If we do standard json encode, I will get some thing like below:

[{"name":"tarun","id":"1"},{"name":"tarun","id":"2"},{"name":"tarun","id":"3"}]

But I was output something like below

[{"name" : "tarun", "ids" : [{"id": "1"},{"id": "2"},{"id": "3"}]}]

Please ignore my syntax mistakes (if any), But I hope my ques makes sense. I am using PHP as my backend scripting language.

You're probably doing something like

SELECT name, id FROM ...

and

$data = array();
while ($row = mysql_fetch_assoc($result)) {
   $data[] = $row;
}

Given your desired structure, you'd want

   $data[$row['name']]['ids'][] = array('id' => $row['id']);

This won't give you your exact structure, but it would be put all the ids as a child-array beneath an array keyed by the tarun field value.

Extending @Marc B's answer

// Getting per person id's list
$people = array();
while ($row = mysql_fetch_assoc($result)) {
    $people[$row['name']][] = array('id' => $row['id']);
}

// Encoding as JSON
$output = "[";

foreach ($people as $name => $ids) {
    $output .= '{"name" : "'.$name.'", ids: [';
    foreach ($ids as $key => $id) {
        $output .= '{"id" : "'.$id.'"},';
    }
    rtrim($output, ",");
    $output .= ']},';
}
rtrim($output, ",");
$output .= ']';

echo $output;

The solution above is specific to the question. A generic JSON Encode method for this problem in my opinion is very tough or not possible.

I suggest to do the query with orderying by name, then when you read the rows, just do a simple check to see if the $row['name'] has changed, if so add the id's youve collected to the php object.

$curName="";
$curIds=array();
$betterJ=array();
$result = mysql_query ("SELECT name,id FROM mytable WHERE 1 ORDER BY NAME);
while($row=mysql_fetch_array($result)
{
    if($curName=="")
        $curName=$row['name']

    if($row['name']!=$curName){
        $betterJ[]=array($name=>$curName,$ids=>$Ids)
        $curName=$row['name']
        $curIds=array()
    }
    $Ids[]=$row['id];
}
$betterJ[]=array($name=>$curName,$ids=>$Ids);
echo json_encode($betterJ);

this might have a typo or something since I wrote it here, but it should produce json like

[ [name:"tarus1",ids:[1,2,3]], [name:"tarus2",ids:[4,5,6], ... ]  

which you would work great in a template in html etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM