猿问

在 Javascript 中使用 PHP 二维数组

在 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');

仍然在 php 部分我为 js 准备了数组


$MAarrayForJS = json_encode(json_encode($MAForJS));

在 javascript 部分,我创建了一个 js-array


var MAarray = new Array(<?php echo $MAarrayForJS; ?>); alert(MAarray)

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[0]);

例如,我试图通过此代码获取 Hans 的名字


var FirstName = MAarray[0][2][1];

这导致 console.log 中的“未定义”。


如何访问特定数组中的特定值,在这种情况下,将 var FirstName 设置为第三个“子数组”中的值“Hans”?


烙印99
浏览 203回答 3
3回答

温温酱

请注意,数组是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]);

慕虎7371278

你在找这个……?$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>&nbsp; &nbsp; var MAarray = <?php echo $MAarrayForJS; ?>;&nbsp; &nbsp; console.log(MAarray[0][0]); // Max</script>

MMTTMM

尝试var&nbsp;FirstName&nbsp;=&nbsp;MAarray[2][1];您似乎正在尝试访问二维数组的第三层。
随时随地看视频慕课网APP
我要回答