user2886519 user2886519 - 3 months ago 27
JSON Question

Multidimensional array PHP-JSON

How to create an array in PHP that with json_encode() becomes a thing with following structure:

Array(
[1] => Array(
[id] => 1
[data] => 45
)
[2] => Array(
[id] => 3
[data] => 54
)
);

Answer

Try something like this:

//initialize array
$myArray = array();

//set up the nested associative arrays using literal array notation
$firstArray = array("id" => 1, "data" => 45);
$secondArray = array("id" => 3, "data" => 54);

//push items onto main array with bracket notation (this will result in numbered indexes)
$myArray[] = $firstArray;
$myArray[] = $secondArray;

//convert to json
$json = json_encode($myArray);