php - See specific data of array
Get the solution ↓↓↓How could you see the first note of 'person1', the second note of 'person2' and the third note of 'person3'?
I've been trying it this way but it does not work for me. $ student ['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])
Answer
Solution:
If I'm interpreting your question correctly, you are asking how to target particular elements of a multidimensional array:
<?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
Output:
1
5
9
Answer
Solution:
Seems like you can alter your loop to include theindex
and use the pattern you described to target the correct note based on your index position:
foreach ($data as $index => $student) {
echo "<br>";
echo $student['name']." " . "= ";
echo $student['notes'][$index];
echo "<br>";
}
You have to make sure you will always have as many notes as the index you accessing thought
Answer
Solution:
<?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>';
}
And the output is:
person1 = 1
person2 = 5
person3 = 9
The way to solve this is simple use a counter. So for every loop you make you increase the counter by 1 and you point to that array field using your counter as an array key.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: composer detected issues in your platform: your composer dependencies require a php version ">= 8.0.2".
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.