0

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.

0

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.