php递归数据转二维数组

1.核心代码

//把递归的数组转二维数组
 function arrDepth($data, $children)
{
    // 获取key列表
    $keyLists = array_keys($data);
    // 获取数组长度
    $count = count($keyLists);
    foreach ($data as $key => $value) {
        if (!is_array($value)) {
            return $data;
        }
        if (key_exists($children, $value)) {
            // 查找当前key在key列表中的key
            $index = array_search($key, $keyLists);
            $index++;
            // 插入子数组
            // 判断插入位置是否存在
            if ($index >= $count) {
                // 如果不存在
                $data = array_merge($data, $value[$children]);
            } else {
                // 如果存在
                $doing = array_splice($data, $keyLists[$index], 0, $value[$children]);
            }
            // 删除之前的子数组
            unset($data[$key][$children]);
            // 重新调用该方法
            $data = arrDepth($data, $children);
            // 返回操作结果
            // 如果不重新循环会出现key值错误的问题
            return $data;
        }
    }
    return $data;
}

2.调用

//把递归的数组转二维数组
$branches2 = arrDepth($branches, 'children');

3.说明

children是保存下级的数组

你可能感兴趣的:(php)