0

I am trying to get my JSON output like this.

{"allterms":[{"group":{"Name":"Test 1"},{"group":{"Name":"Test2","Id":"298"}}]

My current code is

while($r = mysql_fetch_assoc($rs)) {
$rows['allterms']['group'][] = $r;   
}

Which gives me this

{"allterms":{"group":[{"Name":"Test1", "Id":"1740"},{"Name":"Test2","Id":"631"}}]

How can I adjust my code so that each item has a parent term group.

2
  • 1
    Try $rows['allterms'][]['group'], should give you an array of objects Commented May 18, 2014 at 16:40
  • Many thanks Kingkero, since it wasn't formed as answer I couldn't accept it as the right one so I accepted AD7six's below. But thanks! Commented May 18, 2014 at 22:11

2 Answers 2

1

Change the loop like so:

while($r = mysql_fetch_assoc($rs)) {
    $rows['allterms'][]['group'] = $r;   
}

which will generate:

array(
    'allterms' => array(
        0 => array(
            'group' => array(...),
        ),
        1 => array(
            'group' => array(...),
        )
        ...
    )

which as json will be:

{
  "allterms": [
    {
      "group": {
        {
          "Name": "Test1",
          "Id": "1740"
        },
    {
      "group": {
        {
          "Name": "Test2",
          "Id": "631"
        }
     }
   ]
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could use the array_push() function from PHP.

while($r = mysql_fetch_assoc($rs)) {
    array_push($rows['allterms'], $r);   
}

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.