简体   繁体   中英

php multi dimensional array to javascript not accesible through loop

I am trying to pass a multidimensional array from php(values inserted dynamically in real scenario) to javascript and later those values are used inside the javascript, when I am trying to print the same using loop, the values are not getting printed, when I have checked the array[0].length it is shown undefined

Values getting printed when used with static indexes. PFB image for reference - 在此处输入图片说明

Could anyone please correct me where's my mistake, I have been trying to figure this out from long time, unable to get it to work. Any help is appreciated. Thanks.

<?php
// PHP array
$myArray = array();
$myArray[] = array("id" => 1, "data" => 45);
$myArray[] = array("id" => 3, "data" => 54);
$myArray[] = array("id" => 2, "data" => 69);

$json = json_encode($myArray);
echo $json;
?>


<script type='text/javascript'>
// pass PHP array to JavaScript 
var books = <?php echo json_encode($myArray, JSON_PRETTY_PRINT) ?>;


// how to access 
for (var i=0;i<books.length;i++){
    for (var j=0;j<Object.keys(books[i]).length;j++){
       document.write("In Loop: "+books[i][j]);
    }
} 

console.log("Books length: "+books.length+"\n");
console.log("Books[0] length: "+books[0].length+"\n");

console.log("Out Loop: "+books[0]["id"]+"\n");
console.log("Out Loop: "+books[0]["data"]+"\n");
console.log("Out Loop: "+books[1]["id"]+"\n");
console.log("Out Loop: "+books[1]["data"]+"\n");
console.log("Out Loop: "+books[2]["id"]+"\n");
console.log("Out Loop: "+books[2]["data"]+"\n");
</script>

In your example books[i] is an object. It has properties id and data .

But j in the loop is an integer so as example books[0][0] is undefined since the object has no property named "0" .

If you want to loop over the properties of each books[i] object you can use a simple for in loop:

 var books =[ {id:1, data:45}, {id:3, data:54}, {id:2, data:69} ]; // how to access for (var i=0;i<books.length;i++){ for (var prop in books[i]){ document.write("In Loop: " + prop + '=' + books[i][prop] +'<br>'); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM