首页 > 解决方案 > 查看数组的具体数据

问题描述

你怎么能看到“person1”的第一个音符、“person2”的第二个音符和“person3”的第三个音符?

我一直在尝试这种方式,但它对我不起作用。$学生['笔记'] [0] [1])

$person1 = [
   'name' => 'person1',
   'notes' => [1,2,3]
];

$person2 = [
   'name' => 'person2',
   'notes' => [4,5,6]
];

$person3 = [
   'name' => 'person3',
   'notes' => [7,8,9]
];

$data=[$person1,$person2,$person3];


foreach ($data as $student) {

   echo "<br>";
   echo $student['name']." " . "= ";
   echo implode (', ', $student['notes']);
   echo "<br>";
}


//Result
//person1 = 1, 2, 3
//person2 = 4, 5, 6
//person3 = 7, 8, 9


//Expected
//person1 = 1 (see the first 'note' data)
//person2 = 5 (see the second data of 'notes')
//person3 = 9 (see the third data of 'notes')


// It does not work with this form but can it be something like that?
// $student['notes'][0][1])

标签: phparrays

解决方案


似乎您可以更改循环以包含index并使用您描述的模式根据您的索引位置定位正确的音符:

foreach ($data as $index => $student) {

   echo "<br>";
   echo $student['name']." " . "= ";
   echo $student['notes'][$index];
   echo "<br>";
}

您必须确保您始终拥有与您访问的索引一样多的笔记


推荐阅读