我想在多维关联数组中搜索特定记录。当我从第一个数组中搜索记录时,它可以正常工作,但在第二个数组中进行搜索时,它不能正常工作。
这是我的代码:
<?php
$year= array("January"=>array("Ben","Katty","Paul"),
"December"=>array("Ali","Adnan","Sajjad")
);
$match="Ali";
$notThere = True;
foreach ($year as $month => $person) {
foreach ($person as $subjectName => $ID) {
if($match==$ID){
echo "${ID}. borns on ${month}<br>";
$notThere = false;
}
}
if($notThere){
echo "Not Found";
$notThere=false;
}
}
?>
不是FoundAli。出生于12月
此外,如果您能解释嵌套的foreach
循环是如何工作的。
您需要将If语句移出循环
<?php
$year= array("January"=>array("Ben","Katty","Paul"),
"December"=>array("Ali","Adnan","Sajjad")
);
$match="Ali";
$notThere = True;
foreach ($year as $month => $person) {
foreach ($person as $subjectName => $ID) {
if($match==$ID){
echo "${ID}. borns on ${month}<br>";
$notThere = false;
}
}
}
if($notThere){
echo "Not Found";
$notThere=false;
}
?>