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


PHP - Get path by searching array tree by another multidimensional array

我的问题类似于在更大的数组树 - 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
  • 在多维数组中查找值和键
  • 在 php 中查找多维数组中的所有二级键
  • 在另一个更大的数组中查找一个数组
  • 如何在PHP的多维数组中按键=>值进行搜索
  • 在多维数组中搜索键,然后使用 PHP 更改值
  • 如何在 Python 列表列表中找到项目的位置?
此递

归函数搜索多维数组中值的第一个匹配项,并将该值的路径作为键数组返回。

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;
}

小提琴

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
)