in php I have this array
$MAtoJS[] = array('Max','Mustermann','N','A80');
$MAtoJS[] = array('Michaela','May','N','A78');
$MAtoJS[] = array('Hans','Gerstelhuber','N','M12');
$MAtoJS[] = array('Alfred E.','Neumann','N','T25');
$MAtoJS[] = array('James','Bond','N','M72');
Still in the php part I prepare the array for js
$MAarrayForJS = json_encode(json_encode($MAForJS));
In the javascript part I create a js-array
var MAarray = new Array(<?php echo $MAarrayForJS; ?>); alert(MAarray)
The content of MAarray is
[["Max","Mustermann","N","A80"],["Michaela","May","N","A78"],["Hans","Gerstelhuber","N","M12"],["Alfred E.","Neumann","N","T25"],["James","Bond","N","M72"]]
using
console.log(MAarray[0]);
I tried to get for example the first name of Hans by this code
var FirstName = MAarray[0][2][1];
which results in "undefined" in the console.log.
How can I access to a specific value in a specific array, in this case to set the var FirstName to the value "Hans" from the third "subarray"?
Are you looking for this... ?
$MAtoJS = [];
$MAtoJS[] = array('Max','Mustermann','N','A80');
$MAtoJS[] = array('Michaela','May','N','A78');
$MAtoJS[] = array('Hans','Gerstelhuber','N','M12');
$MAtoJS[] = array('Alfred E.','Neumann','N','T25');
$MAtoJS[] = array('James','Bond','N','M72');
$MAarrayForJS = json_encode($MAtoJS);
?>
<script>
var MAarray = <?php echo $MAarrayForJS; ?>;
console.log(MAarray[0][0]); // Max
</script>
Please note that the array is 2 dimensional and not 3 dimensional you're accessing the 3rd dimension which will always yield undefined, have a look at below code snippet in which the value is fetched, altered as per the requirement:
let MAarray = [["Max","Mustermann","N","A80"],["Michaela","May","N","A78"],["Hans","Gerstelhuber","N","M12"],["Alfred E.","Neumann","N","T25"],["James","Bond","N","M72"]]; console.log(MAarray[2][0]); MAarray[2][0] = "New Name"; console.log(MAarray[2][0]);
For some reason you are using json_encode 2 times. You only need to use it once.
Change following
$MAarrayForJS = json_encode(json_encode($MAForJS));
To
$MAarrayForJS = json_encode($MAtoJS);
Then in the JS you can use console.log(MAarray[0][2][1]);
Try
var FirstName = MAarray[2][1];
It seems like you are trying to access the third level of a two dimensional array.
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.