PHP:检查嵌套数组值是否存在于另一个数组中,同时忽略其他值
考虑到以下干草堆和针:PHP:检查嵌套数组值是否存在于另一个数组中,同时忽略其他值,php,arrays,Php,Arrays,考虑到以下干草堆和针: $haystack = array( 'foo' => array( 1 => 'one', 2 => 'two', 3 => 'three', ), ); $needle = array( 'foo' => array( 1 => 'one', 2 => 'two', ), ); 我想检查指针的所有嵌套键值对是否都出现在干草堆中(如上面的示例所示),同时忽略干草堆中可能
$haystack = array(
'foo' => array(
1 => 'one',
2 => 'two',
3 => 'three',
),
);
$needle = array(
'foo' => array(
1 => 'one',
2 => 'two',
),
);
我想检查指针的所有嵌套键值对是否都出现在干草堆中(如上面的示例所示),同时忽略干草堆中可能存在的任何其他键值对(如示例中的$haystack['foo'][3]
)
有很多类似的问题,但我还没有找到一个解决这个特定用例的方法。是否有(组合)标准PHP函数来实现这一点?最优雅的解决方案是什么
[更新]
我还没有明确表示数组可能并不总是具有相同的深度。此外,数组中元素的键可能每次都不同。将告诉您匹配的值。只需确保与您的$pinder
匹配即可
echo $needle['foo'] === array_intersect($needle['foo'], $haystack['foo']);
这是我自己想出来的。它是有效的,但它似乎比它应该的更复杂
/**
* Helper function which recursively checks if the key-value pairs in one array
* are all present in another array. If all key-value pairs in the needle are
* present in the haystack, and the haystack also contains additional items,
* the check wil still pass.
*
* @param array $needle
* The array with the key-value pairs to look for.
* @param array $haystack
* The array in which to look for the key-value pairs.
* @return bool
* TRUE if all key-value pairs of the needle occur in the haystack. FALSE if
* one or more keys or values are missing or different.
*/
function array_contains(array $needle, array $haystack) {
// First, check if needle and haystack are identical. In that case it's easy.
if ($needle === $haystack) {
return TRUE;
}
foreach ($needle as $key => $value) {
// If the key does not occur in the haystack, we're done.
if (!isset($haystack[$key])) {
return FALSE;
}
// If the value is an array...
if (is_array($value)) {
// ...see if the counterpart in $haystack is an array too...
if (!is_array($haystack[$key])) {
return FALSE;
}
// ...and if so, recurse.
if (array_contains($value, $haystack[$key]) == FALSE) {
return FALSE;
}
}
// If the values are not arrays and not the same, the check fails.
else if ($value != $haystack[$key]) {
return FALSE;
}
}
// If we still didn't fail, all tests have passed.
return TRUE;
}
你应该展示你的努力。我发布了一个答案,但被删除了,因为我更喜欢回答显示努力的问题。所以,你想检查
$needle
是否在$haystack
?@johncode我知道,我会发布我的答案。@sam_io是的,这就是我想知道的,将两个数组的所有嵌套级别都考虑在内。@marcvangend我试过了:/遗憾的是,这太棘手了,我没有时间。这是一个非常有趣的挑战。祝你好运:)+1
回答这个问题。如果我没弄错的话,这只适用于一层深度的数组,对吗?如果我更改了值,我仍然会得到一个匹配值。那么,如果草堆和针不总是有相同的深度呢?如果foo元素并不总是被称为foo呢?如果它是一个嵌套数组,那么这将不起作用,并且没有“优雅”的方法来实现这一点。数组键在代码中显然是动态的。我认为这是可以按照OP的要求来实现的,但至少需要10行代码。但是,此答案不启用动态键或更高的深度。请修改OP以添加此选项。@JayBlanchard我以前曾因在问题中包含可能的答案而受到mods的批评,告诉我这应该是答案。。。