【问题标题】:PHP - Get path by searching array tree by another multidimensional arrayPHP - 通过另一个多维数组搜索数组树来获取路径
【发布时间】:2013-10-30 10:39:12
【问题描述】:

我的问题与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;
}

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

我发现的类似问题:

【问题讨论】:

标签: php arrays algorithm multidimensional-array


【解决方案1】:

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

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
)

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    • 2019-10-16
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多