检查另一个数组中的键值对是否存在于另一个数组中-具有不同的键名(php) [英] Check if key-value pair from one array exists in another – with different key name (php)
问题描述
我正在编辑此问题,因为我的数组实际上应该是多维数组。
I am editing this question as my arrays should in fact have been multidemensional arrays.
我希望通过 $ array_food 进行迭代。我想打印 snack->'banana'的值,但仅当 food->'banana'存在于单独的数组 $ array_healthyfood 。
I wish to iterate though $array_food. I would like to print the the value of snack->'banana' but only if food->'banana' exists in a separate array, $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; ?>
任何指针都会受到赞赏。
Any pointers appreciated.
推荐答案
如何确定健康食品数组中是否存在一个特定项目:
How to figure out whether one particular item exists in the healthy foods array:
array_reduce($healthyFood, function ($exists, array $hf) {
return $exists || $hf['food'] == 'Banana';
})
(这可以通过普通循环,自定义函数或许多其他方式来完成。我在这里选择了函数数组归约。)
(This can be done with a normal loop, or a custom function, or many other ways. I've chosen a functional array reduction here.)
如何对数组中的每个项目执行此操作:
How to do this for each item in an array:
foreach ($foods as $food) {
$exists = array_reduce($healthyFood, function ($exists, array $hf) use ($food) {
return $exists || $hf['food'] == $food['snack'];
});
if ($exists) ..
}
如何过滤食物按健康食品分类:
How to filter the food array by healthy foods:
$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'];
});
});
与连续循环健康食品阵列相比,如何更有效地做到这一点:
How to do this more efficiently than continuously looping the healthy foods array:
$healthyFoods = array_map(function (array $hf) { return $hf['food']; }, $healthyFoods);
foreach ($foods as $food) {
if (in_array($food['snack'], $healthyFoods)) ...
}
这篇关于检查另一个数组中的键值对是否存在于另一个数组中-具有不同的键名(php)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!