这可能很简单,但我试图解决这个问题时遇到了一点灾难。我在PHP中有一个关联数组,如下所示:
$people= array (["Name" => "Sandra", "Age" => "21"], ["Name" => "Frank", "Age" => "34"], ["Name" => "Marc", "Age" => "56"]);
现在,如果我想知道数组中两个已知元素的年龄,那就说,桑德拉和弗兰克。我试着这样做:
foreach($people as $i){
foreach($i as $info => $v){
if($info == "Name"){
if($v == "Sandra" || $v == "Frank"){
echo $v." has ". $v;
}
}
}
}
结果是:桑德拉有桑德拉。但这当然不是应该印刷的东西。有人能让我理解这个简单的问题吗?
答案 0 :(得分:2)
为什么2个foreach循环,你可以通过一个foreach循环来实现它:
$people = array(["Name" => "Sandra", "Age" => "21"], ["Name" => "Frank", "Age" => "34"], ["Name" => "Marc", "Age" => "56"]);
foreach ($people as $v) {
if ($v["Name"] == "Sandra" || $v["Name"] == "Frank") {
echo $v["Name"] . " has " . $v["Age"];
echo "<br />";
}
}
<强>输出:强>
Sandra has 21
Frank has 34
答案 1 :(得分:1)
首先,您正在使用两种在PHP中使用数组的约定。它有时变得不清楚,所以只使用一个约定,例如:
$people= [["Name" => "Sandra", "Age" => "21"], ["Name" => "Frank", "Age" => "34"], ["Name" => "Marc", "Age" => "56"]]
或
$people= array(array("Name" => "Sandra", "Age" => "21"), array("Name" => "Frank", "Age" => "34"), array("Name" => "Marc", "Age" => "56"))
您的问题有解决方案:
foreach($people as $person)
if($person['Name'] == "Sandra" || $person['Name'] == "Frank")
echo $person['Name'] . ' has ' . $person['Age'];
答案 2 :(得分:0)
试试这个:
$flag = false;
foreach($people as $i){
foreach($i as $info => $v){
if($info == "Name"){
if($v == "Sandra" || $v == "Frank"){
echo $v." has ";
$flag = true;
}
else
$flag = false;
}
if($info == "Age" && $flag){
echo $v;
}
}
}