我有两个关联数组,我想检查是否
$array1["foo"]["bar"]["baz"] exists in $array2["foo"]["bar"]["baz"]
值无关紧要,只是“路径”。array_ intersect_ assoc做我需要的吗?
如果不是我自己怎么写?
我有两个关联数组,我想检查是否
$array1["foo"]["bar"]["baz"] exists in $array2["foo"]["bar"]["baz"]
值无关紧要,只是“路径”。array_ intersect_ assoc做我需要的吗?
如果不是我自己怎么写?
试试这个:
<?php
function array_path_exists(&$array, $path, $separator = '/')
{
$a =& $array;
$paths = explode($separator, $path);
$i = 0;
foreach ($paths as $p) {
if (isset($a[$p])) {
if ($i == count($paths) - 1) {
return TRUE;
}
elseif(is_array($a[$p])) {
$a =& $a[$p];
}
else {
return FALSE;
}
}
else {
return FALSE;
}
$i++;
}
}
// Test
$test = array(
'foo' => array(
'bar' => array(
'baz' => 1
)
),
'bar' => 1
);
echo array_path_exists($test, 'foo/bar/baz');
?>
如果您只需要检查密钥是否存在,则可以使用简单的 if 语句。
<?php
if (isset($array1["foo"]["bar"]["baz"]) && isset($array2["foo"]["bar"]["baz"]
)) { //存在 }