PHP - 通过另一个多维数组搜索数组树来获取路径

时间:2013-10-30 10:39:12

标签: php arrays algorithm multidimensional-array

我的问题类似于Searching for an array key branch inside a larger array tree - PHP,但是对于不同的限制(如处理中的处理等)以及为什么不为了知识而我只想使用PHP递归来实现它。

考虑这些数据:

array(
    'root_trrreeee1' => array(
        'path1' => array(
            'description' => 'etc',
            'child_of_path_1' => array(
                array('name' => '1'),
                array('name' => '1')
            )
        ),
        'path1' => array(
            'description' => 'etc',
            'child_of_path_1' => array(
                array('name' => '1'),
                array('name' => '1')
            )
        ),
    ),
    'name' => '1',
    1 => array('name' => '1'),
    'another_leaf' => '1'
)

如果我搜索array('name' => '1'),它应返回我需要遍历的路径以获取该值root_trrreeee1.path1.child_of_path_1.o,最好以数组形式返回:

array(
    0 => root_trrreeee1
    1 => path1
    2 => child_of_path_1
    3 => 0
)

这是我试图实现的递归函数,但它不起作用:

function multidimensional_preserv_key_search($haystack, $needle, $path = array(), &$true_path = array())
{
    if (empty($needle) || empty($haystack)) {
        return false;
    }

    foreach ($haystack as $key => $value) {

        foreach ($needle as $skey => $svalue) {

            if (is_array($value)) {
                $path = multidimensional_preserv_key_search($value, $needle, array($key => $path), $true_path);
            }

            if (($value === $svalue) && ($key === $skey)) {
                $true_path = $path;
                return $true_path;
            }
        }

    }

    if (is_array($true_path)) { return array_reverse(flatten_keys($true_path)); }
    return $path;
}


function flatten_keys($array)
{
    $result = array();

    foreach($array as $key => $value) {
        if(is_array($value)) {
            $result[] = $key;
            $result = array_merge($result, self::flatten_keys($value));
        } else {
            $result[] = $key;
        }
    }

    return $result;
}

它只返回一个空数组。 提前谢谢。

我发现的类似问题:

1 个答案:

答案 0 :(得分:0)

此递归函数搜索多维数组中第一次出现的值,并将其路径作为键数组返回。

function array_value_path($array, $needle, &$path)
{
    foreach($array as $key => $value) {
        if ($value == $needle || is_array($value) && array_value_path($value, $needle, $path)) {
            array_unshift($path, $key);
            return true;
        }
    }
    return false;
}

fiddle

array_value_path($a, ['name' => 1], $path);

Array
(
    [0] => root_trrreeee1
    [1] => path1
    [2] => child_of_path_1
    [3] => 0
)

array_value_path($a, 1, $path);

Array
(
    [0] => root_trrreeee1
    [1] => path1
    [2] => child_of_path_1
    [3] => 0
    [4] => name
)