在Javascript中使用PHP二维数组

时间:2019-07-17 05:50:07

标签: javascript php arrays

在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数组

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

我试图通过此代码获得汉斯的名字

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

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

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

4 个答案:

答案 0 :(得分:1)

您在寻找这个吗...?

$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>

答案 1 :(得分:1)

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

答案 2 :(得分:0)

由于某种原因,您使用json_encode 2次。您只需要使用一次。

更改以下内容

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

收件人

$MAarrayForJS = json_encode($MAtoJS);

然后在JS中,您可以使用console.log(MAarray [0] [2] [1]);

答案 3 :(得分:0)

尝试

var FirstName = MAarray[2][1];

似乎您正在尝试访问二维数组的第三级。