Associative array to JSON [closed]
Asked Answered
F

2

15

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?

Fougere answered 5/6, 2012 at 0:23 Comment(4)
Documentation: Read it. Love it. Use it.Shirt
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?Libbi
Show your coding attempts. Did you try simply $output["L"] = $sql_result; instead of array_push?Sim
Mmm, you get the array of rows from the database and then use json_encode on it. The question isn't very clearJuliettajuliette
A
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);
Antigen answered 5/6, 2012 at 8:7 Comment(0)
V
3

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

json_encode($arr);
Varus answered 5/6, 2012 at 0:26 Comment(5)
OP presumably knows about that function. The question is about construing the $arr variable.Sim
"OP presumably knows about that function." "Objection, Your Honor! Presuming facts not in evidence!" "Sustained."Shirt
Handcuffs! Send the convict into the manual prison. Unanimous jury decision!Sim
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?Fougere
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.Varus

© 2022 - 2024 — McMap. All rights reserved.