PHP'den JavaScript'e Çok Boyutlu Dizileri Göndermek

Previously we demonstrated how the json_encode function can be used to pass PHP arrays to JSON strings and JavaScript arrays. On this page we continue the demonstration with multidimensional arrays. One array is numerically indexed, two others are mixed numerical and associative.

Whether your PHP array is single or multi-level or whether it is numerically indexed or associative, the following, placed inside a JavaScript segment, will output it to JavaScript:

var ar = <?php echo json_encode($ar) ?>;

You will likely want to use JavaScript's JSON.parse to handle the results of PHP's json_encode, in which case you would use the following instead, as one of the examples below demonstrates:

var ar = JSON.parse( '<?php echo json_encode($ar) ?>' );

For the example arrays below, first we show the array in PHP, then we include the JavaScript segment where json_encode is used to output it, then we display the output, commented out. And lastly, we show the syntax used to access the resulting array elements or object properties in JavaScript.

Array Example One

The first example array has two levels, both numerically indexed.[1]

<?php
// PHP array
$products = array(
    // product abbreviation, product name, unit price
    array('choc_cake', 'Chocolate Cake', 15),
    array('carrot_cake', 'Carrot Cake', 12),
    array('cheese_cake', 'Cheese Cake', 20),
    array('banana_bread', 'Banana Bread', 14)
);
?>
<script type="text/javascript">
// pass PHP array to JavaScript array
var products = <?php echo json_encode( $products ) ?>;

// result seen through view source
// var products = [["choc_cake","Chocolate Cake",15],["carrot_cake","Carrot Cake",12],["cheese_cake","Cheese Cake",20],["banana_bread","Banana Bread",14]];

// how to access elements in multi-dimensional array in JavaScript
alert( products[0][1] ); // Chocolate Cake
</script>

Numerically indexed PHP arrays are output by json_encode as array literals in JavaScript by default.[2] Associative PHP arrays are output as object literals.

The following demonstrates how to access elements in the multi-dimensional numerically indexed array:

alert( products[0][1] ); // Chocolate Cake

When you output a PHP array into JavaScript you can see the result using the browser View Source menu command. This is displayed above in the commented-out line:

// var products = [["choc_cake","Chocolate Cake",15],["carrot_cake","Carrot Cake",12], ...

Notice that the json_encode output includes no white space. You can include an optional JSON_PRETTY_PRINT parameter[3] to include spaces and carriage returns in the output for easier viewing. The next example demonstrates this.

Array Example Two

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>

The following demonstrates how to access a property in the array of objects:

// to access author of 2nd book
console.log( books[1].author ); // David Flanagan

Array Example Three

The PHP array for this example is also mixed. The outer level is associative; the inner level is mixed with most entries numerically indexed except for the vegetables sub-array:

<?php
$food_groups = array(
    'meat' => array(),
    'vegetables' => array(
        'leafy' => array('collard greens', 'kale', 'chard', 'spinach', 'lettuce'),
        'root' => array('radish', 'turnip', 'potato', 'beet'),
        'other' => array('brocolli', 'green beans', 'corn', 'tomatoes')
    ),
    'grains' => array('bread', 'rice', 'oatmeal'),
    'legumes' => array('kidney beans', 'lentils', 'split peas'),
    'fruits' => array('apple', 'raspberry', 'pear', 'banana'),
    'sweets' => array('cookies', 'brownies', 'cake', 'pie'),
);
?>

This example demonstrates using JSON.parse on the output of json_encode. The PHP tags are enclosed in single quotes for this[4]:

<script type="text/javascript">
// using JSON.parse with json_encode
var food_groups = JSON.parse( '<?php echo json_encode($food_groups) ?>' );

// JSON_PRETTY_PRINT not used since it would trigger error with JSON.parse

/* output manually formatted so you can read it
{
    "meat":[],
    "vegetables":{
        "leafy":["collard greens","kale","chard","spinach","lettuce"],
        "root":["radish","turnip","potato","beet"],
        "other":["brocolli","green beans","corn","tomatoes"]
    },
    "grains":["bread","rice","oatmeal"],
    "legumes":["kidney beans","lentils","split peas"],
    "fruits":["apple","raspberry","pear","banana"],
    "sweets":["cookies","brownies","cake","pie"]
}
*/

// demonstrating access
console.log( food_groups['vegetables']['leafy'][0] ); // collard greens
console.log( food_groups.sweets[1] ); // brownies
</script>

We can't use JSON_PRETTY_PRINT with JSON.parse since that would result in a JavaScript error: unterminated string literal.

The following demonstrates access to the object properties and array elements. Notice that dot syntax or square bracket notation can be used with object properties:

alert( food_groups['vegetables']['leafy'][0] ); // collard greens
alert( food_groups.sweets[1] ); // brownies

The above example would not need to use JSON.parse. The means of access demonstrated with console.log and alerts would be the same whether JSON.parse was used or not. So how do you know when or whether you should use JSON.parse? Read on for more information on the subject.

 


  1. The products list is borrowed from a PHP Order Form example. ^
  2. You can use the JSON_FORCE_OBJECT option to output numerically indexed PHP arrays as object literals if you prefer. ^
  3. The PHP documentation for json_encode provides a list of options available. ^
  4. When using JSON.parse you enclose the PHP tags in single quotes since JSON names and values are enclosed in double quotes. ^

 

Kaynak

Yorumunuzu Ekleyin


Yükleniyor...
Yükleniyor...