Home > Backend Development > PHP Tutorial > php 数组获取父节点

php 数组获取父节点

WBOY
Release: 2016-06-06 20:26:41
Original
1786 people have browsed it

比如一个数组里包括地名,你已经知道了石家庄,怎么知道它的上级河北。或者你已经知道了北京,怎么知道它的上级中国

回复内容:

比如一个数组里包括地名,你已经知道了石家庄,怎么知道它的上级河北。或者你已经知道了北京,怎么知道它的上级中国

用id做数组的键 每项里面包括parent_id

最近刚好写了一份获取n维数组某个节点的深度和父级节点的代码,希望对题主有用

<code>class ArrayUtil {
    /**
     * 深度优先遍历查找一个树形结构中,某个节点的所在位置
     *
     * 参数例子:
     * $input: [
     *   'a' => [
     *     'b' => [
     *       'c' => []
     *     ]
     *   ],
     *   'd' => [
     *   ]
     * ]
     * $target: c
     * 返回值: [3, ['a','b','c']]
     *
     * 可以用list($level, $pathKeys) = self::getNodeLevel(....)来进行使用
     * $level表示层级
     * $pathKeys表示访问到这个节点需要经过的key
     *
     * @param array $input 输入
     * @param string $target 希望查找的节点(key或者value),例如 'f'
     * @param array $pathKeys 节点数组列表
     * @return null|array [$level, [$pathKey0, $pathKey1, ...]] 没有找到时会返回空
     */
    public static function getNodeLevel(array $input, $target, array $pathKeys = [])
    {
        foreach ($input as $key => $val) {
            $pathKeys[] = $key;

            if ($key == $target) {
                return [count($pathKeys), $pathKeys];
            } elseif (is_array($val)) {
                //当前范围没有找到值,递归进入下一层
                $result = self::getNodeLevel($val, $target, $pathKeys);
                if ($result) {
                    return $result;
                }
            }

            array_pop($pathKeys);
        }
        return null;
    }
}</code>
Copy after login

使用:

<code>$input = [
    'a' => [
        'b' => [
            'c' => ['hello', 'world']
        ]
    ],
    'd' => [
    ]
];
list($depth, $parents) = ArrayUtil::getNodeLevel($input, 'c');
print_r($depth); //层级,输出3
echo "\n";
print_r($parents);
/*
父级节点,输出
Array
(
    [0] => a
    [1] => b
    [2] => c
)
*/

//获得目标节点的子数组
$target = &$input;
foreach ($parents as $key) {
    $target = &$target[$key];
}
print_r($target);
/*
输出子节点
Array
(
    [0] => hello
    [1] => world
)
*/</code>
Copy after login

代码在哪里?

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template