[英]Using PHP two dimensional Array in Javascript
in php I have this array 在PHP中我有这个数组
$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 仍然在php部分中,我为js准备了数组
$MAarrayForJS = json_encode(json_encode($MAForJS));
In the javascript part I create a js-array 在javascript部分中,我创建了一个js-array
var MAarray = new Array(<?php echo $MAarrayForJS; ?>); alert(MAarray)
The content of MAarray is MAarray的内容是
[["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. 在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"? 我如何访问特定数组中的特定值,在这种情况下,如何将第三个“子数组”中的var FirstName设置为值“ Hans”?
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: 请注意,数组是2维的,而不是3维的,您正在访问第3维,它将始终产生未定义的状态,请查看下面的代码片段,在其中提取了值,并根据要求进行了更改:
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. 由于某种原因,您使用json_encode 2次。 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]); 然后在JS中可以使用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. 似乎您正在尝试访问二维数组的第三级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.