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
)
);
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);
Here is a shorter way:
$myArray = array();
$myArray[] = array("id" => 1, "data" => 45);
$myArray[] = array("id" => 3, "data" => 54);
//convert to json
$json = json_encode($myArray);
This example PHP array is mixed, with the outer level numerically indexed and the second level associative:
<?php
// PHP array
$books = array(
array(
"title" => "Professional JavaScript",
"author" => "Nicholas C. Zakas"
),
array(
"title" => "JavaScript: The Definitive Guide",
"author" => "David Flanagan"
),
array(
"title" => "High Performance JavaScript",
"author" => "Nicholas C. Zakas"
)
);
?>
In the json_encode output, the outer level is an array literal while the second level forms object literals. This example demonstrates using the JSON_PRETTY_PRINT option with json_encode for more readable output as shown in code comments below:
<script type="text/javascript">
// pass PHP array to JavaScript
var books = <?php echo json_encode($books, JSON_PRETTY_PRINT) ?>;
// output using JSON_PRETTY_PRINT
/* var books = [ // outer level array literal
{ // second level object literals
"title": "Professional JavaScript",
"author": "Nicholas C. Zakas"
},
{
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan"
},
{
"title": "High Performance JavaScript",
"author": "Nicholas C. Zakas"
}
]; */
// how to access
console.log( books[1].author ); // David Flanagan
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With