[英]PHP: check if nested array values exist in another array, while ignoring additional values
Given the following haystack and needle: 给定以下干草堆和针头:
$haystack = array(
'foo' => array(
1 => 'one',
2 => 'two',
3 => 'three',
),
);
$needle = array(
'foo' => array(
1 => 'one',
2 => 'two',
),
);
I want to check if all nested key-value pairs of the needle occur in the haystack (like it does in the example above), while ignoring any additional key-value pairs that may exist in the haystack (like $haystack['foo'][3]
in the example). 我想检查针的所有嵌套键-值对是否都出现在了干草堆中(就像上面的示例中一样),而忽略了干草堆中可能存在的任何其他键-值对(例如
$haystack['foo'][3]
)。
There are many similar questions on SO but I haven't found a solution for this specific use case. 关于SO有很多类似的问题,但是我还没有找到针对此特定用例的解决方案。 Is there a (combination of) standard PHP functions to do this?
是否有(组合)标准PHP函数来执行此操作? What is the most elegant solution?
什么是最优雅的解决方案?
[update] [更新]
I didn't make clear yet that the arrays may not always have the same depth. 我还没有弄清楚数组可能并不总是具有相同的深度。 Also, the keys of the elements in the arrays may be different every time.
而且,阵列中元素的键每次可能都不同。
array_intersect()
will tell you what values match. array_intersect()
会告诉您哪些值匹配。 Just make sure that matches your $needle
. 只要确保与您的
$needle
相匹配即可。
echo $needle['foo'] === array_intersect($needle['foo'], $haystack['foo']);
This is what I came up with myself. 这就是我自己想到的。 It works, but it seems more complex than it should be...
它可以工作,但似乎比应有的要复杂。。。
/**
* 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.