1

我有两个关联数组,我想检查是否

$array1["foo"]["bar"]["baz"] exists in $array2["foo"]["bar"]["baz"]

值无关紧要,只是“路径”。array_ intersect_ assoc做我需要的吗?
如果不是我自己怎么写?

4

2 回答 2

5

试试这个:

<?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');

?>
于 2009-08-01T22:20:01.060 回答
1

如果您只需要检查密钥是否存在,则可以使用简单的 if 语句。

<?php
if (isset($array1["foo"]["bar"]["baz"]) && isset($array2["foo"]["bar"]["baz"]

)) { //存在 }

于 2009-08-01T20:16:59.890 回答