Учитывая следующий стог сена и иглу:
$haystack = array(
'foo' => array(
1 => 'one',
2 => 'two',
3 => 'three',
),
);
$needle = array(
'foo' => array(
1 => 'one',
2 => 'two',
),
);
Я хочу проверить, находятся ли все вложенные пары ключ-значение иглы в стоге сена (как в примере выше), игнорируя любые дополнительные пары ключ-значение, которые могут существовать в стоге сена (например, $haystack['foo'][3]
в примере).
На SO есть много похожих вопросов, но я не нашел решения для этого конкретного варианта использования. Есть ли (сочетание) стандартных функций PHP для этого? Какое самое элегантное решение?
[Обновить]
Я еще не уточнил, что массивы могут не всегда иметь одинаковую глубину. Кроме того, ключи элементов в массивах могут быть разными каждый раз.
Это то, что я придумал сам. Он работает, но он кажется более сложным, чем должен быть...
/**
* 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 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;
}
array_intersect()
сообщит вам, какие значения соответствуют. Просто убедитесь, что соответствует вашей $needle
.
echo $needle['foo'] === array_intersect($needle['foo'], $haystack['foo']);
$needle
внутри$haystack
??