我想在多维关联数组中搜索特定记录。当我从第一个数组中搜索记录时它工作正常但在第二个数组中搜索时它无法正常工作。
这是我的代码:
<?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;
}
}
?>
Not FoundAli。 12月份出生
另外,如果您可以解释嵌套foreach
循环的工作原理。
答案 0 :(得分:1)
您需要将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;
}
?>