您如何看待“ person1”的第一音符,“ person2”的第二音符和“ person3”的第三音符?
我一直在尝试这种方法,但是对我来说不起作用。 $学生['notes'] [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])
答案 0 :(得分:0)
似乎您可以更改循环以包含index
并使用您描述的模式根据索引位置定位正确的音符:
foreach ($data as $index => $student) {
echo "<br>";
echo $student['name']." " . "= ";
echo $student['notes'][$index];
echo "<br>";
}
您必须确保始终拥有与访问思想索引相同的注释
答案 1 :(得分:0)
<?php
$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];
echo '<pre>';
$counter = 0;
foreach ($data as $student) {
echo $student['name']." " . "= " .$student['notes'][$counter];
$counter++;
echo '<br>';
}
输出为:
person1 = 1
person2 = 5
person3 = 9
解决此问题的方法很简单,使用计数器。因此,对于每个循环,您都需要将计数器增加1,然后使用计数器作为数组键指向该数组字段。
答案 2 :(得分:0)
如果我正确地解释了您的问题,那么您在问如何定位多维数组的特定元素:
<?php
$data =
[
[
'name' => 'person1',
'notes' => [1,2,3]
],
[
'name' => 'person2',
'notes' => [4,5,6]
],
[
'name' => 'person3',
'notes' => [7,8,9]
]
];
echo $data[0]['notes'][0], "\n"; // First note of first person
echo $data[1]['notes'][1], "\n"; // Second note of second person
echo $data[2]['notes'][2], "\n"; // Third note of third person
输出:
1
5
9