Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
)
);
like image 665
user2886519 Avatar asked Oct 18 '13 16:10

user2886519


3 Answers

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);
like image 80
Charles R Avatar answered Nov 12 '22 08:11

Charles R


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);
like image 44
ewwink Avatar answered Nov 12 '22 10:11

ewwink


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>
like image 3
Swatantra Kumar Avatar answered Nov 12 '22 10:11

Swatantra Kumar