我正在编辑这个问题,因为我的数组实际上应该是多维数组。
我希望迭代 $ array_food 。我想打印 snack->'banana'的值,但仅当 food->'banana'存在于一个单独的数组中时, $ array_healthyfood
$array_food = array (
[0] => Array
(
snack => 'banana',
breakfast => 'cereal',
drink => 'water'
)
[1] => Array
(
snack => 'apple',
breakfast => 'eggs',
drink => 'juice'
)
)
$array_healthyfood = array (
[0] => Array
(
food => 'banana',
breakfast => 'cereal',
drink => 'water'
)
[1] => Array
(
food => 'apple',
breakfast => 'eggs',
drink => 'juice'
)
)
我尝试了以下内容:
<?php foreach ($array_food as $foodelement):
if (in_array($foodelement->snack->$fruit, $array_healthyfood)) {
echo $foodelement->snack->$fruit;
}
endforeach; ?>
任何指示赞赏。
答案 0 :(得分:0)
如何确定健康食品阵列中是否存在某个特定项目:
array_reduce($healthyFood, function ($exists, array $hf) {
return $exists || $hf['food'] == 'Banana';
})
(这可以通过普通循环,自定义函数或许多其他方式完成。我在这里选择了函数数组缩减。)
如何为数组中的每个项目执行此操作:
foreach ($foods as $food) {
$exists = array_reduce($healthyFood, function ($exists, array $hf) use ($food) {
return $exists || $hf['food'] == $food['snack'];
});
if ($exists) ..
}
如何通过健康食品过滤食物阵列:
$foods = array_filter($foods, function (array $food) use ($healthyFood) {
return array_reduce($healthyFood, function ($exists, array $hf) use ($food) {
return $exists || $hf['food'] == $food['snack'];
});
});
如何比连续循环健康食品阵列更有效地做到这一点:
$healthyFoods = array_map(function (array $hf) { return $hf['food']; }, $healthyFoods);
foreach ($foods as $food) {
if (in_array($food['snack'], $healthyFoods)) ...
}
答案 1 :(得分:-1)
好的,我还没有对此进行过测试,只是写出来了。可能需要一些调整。我假设你已经测试过你是否真的让$ fruit var恢复正常。
基于数组地图的修订版
<?php
$flipped_healthyfood = array_flip($array_healthyfood);
foreach($arrayfood as $key => $food){
if( isset($flipped_healthyfood[$food]) ){
echo $food;
}
}
?>