14

I would like to be able to generate a JSON output in the following format:

{"a":{"ax":1,"abx":2},"b":{"bax":1,"bbx":2},"c":3,"d":4,"e":5}

Although I have found that the respective code is this:

$arr = array('a' => array('ax' => 1, 'abx' => 2), 'b' => array('bax' => 1, 'bbx' => 2), 'c' => 3, 'd' => 4, 'e' => 5);

, I'm struggling to generate this output by using data from an SQL query. I have tried array_push() and array_merge() and the closest I have managed to get is this:

[{"a":{"ax":1,"abx":2}},{"b":{"bax":1,"bbx":2}}, ....]

How can I do it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nick
  • 151
  • 2
  • 3
  • 12
  • 4
    [Documentation: Read it. Love it. Use it.](http://www.php.net/manual/en/ref.json.php) –  Jun 05 '12 at 00:25
  • Are you asking how to get your SQL query results formatted like that PHP array, or are you asking about how to use `json_encode`? – John Flatness Jun 05 '12 at 00:26
  • 1
    Show your coding attempts. Did you try simply `$output["L"] = $sql_result;` instead of `array_push`? – mario Jun 05 '12 at 00:27
  • Mmm, you get the array of rows from the database and then use json_encode on it. The question isn't very clear – Nicolás Torres Jun 05 '12 at 00:28

2 Answers2

23

First you should query all your data from the table and then move it to an array. After this, use the json_encode($array) function.

Place your array inside the parameters.

Then the output will be in JSON format.

$query = "select *  from employees";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
  $employee = $row['employee'];
  $country = $row['country'];

  $employees[] = array('employee'=> $employee, 'country'=> $country);
}

echo $jsonformat = json_encode($employees);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mghost.friend
  • 382
  • 1
  • 3
  • 5
3

Load the data you want encoded into an array, and then use json_encode():

json_encode($arr);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
None
  • 5,491
  • 1
  • 40
  • 51
  • 2
    OP presumably knows about that function. The question is about construing the `$arr` variable. – mario Jun 05 '12 at 00:28
  • 5
    "OP presumably knows about that function." "Objection, Your Honor! Presuming facts not in evidence!" "Sustained." –  Jun 05 '12 at 00:31
  • Handcuffs! Send the convict into the manual prison. Unanimous jury decision! – mario Jun 05 '12 at 00:33
  • 1
    My problem is that json_encode is introducing [] and it seems that they are interfering with my code. Is there any way to get rid of them? – Nick Jun 05 '12 at 00:43
  • 1
    It's valid JSON. If valid JSON is interfering with your code then you need to rethink what you are doing. There is probably a better way. – None Jun 05 '12 at 00:59