In the following array I would like to search for firstname, eg tom and then echo out the name of the key "library" and "canteen" because there is stored a person with first name tom in both of them.
This is the output of print_r($school);
Array
(
[library] => Array
(
[0] => Array
(
[firstname] => tom
[lastname] => brown
)
)
)
Array
(
[canteen] => Array
(
[0] => Array
(
[firstname] => matt
[lastname] => smith
)
[1] => Array
(
[firstname] => tom
[lastname] => jones
)
)
)
I've done multiple tries with foreach loops without success. I must admit that I'm not completely familiar with the way they work.
This is what I've tried:
foreach ($school as $k => $v) {
if ($v['firstname'] == 'tom'){
echo 'Currently at the '.$k.'<br>';
}
}
This is the output is whish for:
Currently at the library
Currently at the canteen
You'll need another foreach loop
foreach ($school as $k => $v) {
foreach($v as $key => $value){
if ($value['firstname'] == 'tom'){
echo 'Currently at the ' . $k;
}
}
}
The problem is you are only iterating trough the first dimension, but you array is twodimensional. Here is the fixed code:
foreach ($school as $k => $va) { //Iterate trough the array $school($k is the key and $va is the value)
foreach($va as $v) { //Iterate trough $va, this is a multidimensional array. $v is the value.
if ($v['firstname'] == 'tom'){
echo 'Currently at the '.$k; //$k is still storing the key from the first foreach.
}
}
}
Foreach is not hard, but you will need to understand it first. Here is "what the computer says" hen running the code: Ok, Iterate trough the array $school. Now I will store the key library in $k, and value array(...) in $va.
Oh, another foreach... Now I should loop through $va(the value of $school['library']). I should set the $v['firstname'] to 'tom' and the lastname to 'brown'.
The check is ok, echo the key 'library'.
Foreach exits, no more entry in 'library'.
The first foreach is still alive: It should set the $k to canteen and $va to array(...).
Starting new foreach, iterating trough $va($school['canteen']), put key 'canteen' to $k...
$v is now Array("firstname" => "matt", "lastname" => "smith");
Firstname is not 'tom'. Next value from school[canteen].
$v is now Array("firstname" => "tom", "lastname" => "jones");
Firstname is tom, echoing key from $k, it is 'canteen'.
End of array, both foreach exits.
if $school is the outer array then you can do like this:
foreach ($school as $k => $v) {
foreach($v as $key=>$value{
if ($value['firstname'] == 'tom'){
echo 'Currently at the '.$key;
}
}
}
You're using multidimensional array. Therefore, you need to use two foreach loops to loop through each array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.