这应该很简单,但我没有得到预期的结果。浏览器会列出数组中的所有元素(当我包含"!"运算符时)或者不列出任何元素(当我不包含"!时) "运营商)。我只想尝试列出除一个元素以外的所有内容或仅列出一个元素。我无法通过任何一种方式工作。
$features = array(
'winter' => 'Beautiful arrangements for any occasion.',
'spring' => 'It must be spring! Delicate daffodils are here.',
'summer' => "It's summer, and we're in the pink.",
'autumn' => "Summer's over, but our flowers are still a riot of colors."
);
<h1>Labeling Array Elements</h1>
<?php
foreach ($features as $feature) {
if(array_key_exists('autumn', $features)) {
continue;
}
echo "<p>$feature</p>";
}
?>
答案 0 :(得分:2)
当你在循环中执行continue
只是因为它存在于数组中时,它会在第一次迭代时停止。这总是如此。
相反,你需要做这样的事情:
foreach ($features as $season => $description) {
if ($season == 'autumn') {
continue;
}
echo $description;
}
答案 1 :(得分:0)
你也可以使用array_filter来实现这种方法:
$features = array(
'winter' => 'Beautiful arrangements for any occasion.',
'autumn' => "Summer's over, but our flowers are still a riot of colors.",
'spring' => 'It must be spring! Delicate daffodils are here.',
'summer' => "It's summer, and we're in the pink.",
);
print_r(array_filter($features, function ($key) {
return $key != 'autumn';
}, ARRAY_FILTER_USE_KEY));