如何将树形数组,重新组合成一维数组

zhai斋
  • 95
$arr=[
      0 =>[
        "id" =>"2",
        "cate_name" =>"外用",
        "parent_id" => "0",
        "child" => [
          0 => [
            "id" => "5",
            "cate_name" => "外1",
            "parent_id" =>"2",
            "child" =>[
              0 => [
                "id" =>"7",
                "cate_name" => "外外1",
                "parent_id" => "5",
                "child" => NULL
               ]
            ]
          ],
          1=>[
            "id" => "6",
            "cate_name" => "外2",
            "parent_id" => "2",
            "child" => NULL,
          ]
        ]
      ],
      1 => [
        "id" => "3",
        "cate_name" =>"内用",
        "parent_id" => "0",
        "child" => NULL,
      ]
]

将这个三维数组分类树,组合成这种一维数组


$arr=[
    0=>["id" =>"2","cate_name" =>"外用","parent_id" => "0",],  //顶级分类
    1=>["id" => "5","cate_name" => "外1","parent_id" =>"2",],     //二级分类
    2=>["id" =>"7","cate_name" => "外外1","parent_id" => "5",],       //三级分类
    3=>["id" => "6","cate_name" => "外2","parent_id" => "2",],    //二级分类
    4=>["id" => "3","cate_name" =>"内用","parent_id" => "0",],//顶级分类
];

求大神们帮忙。

回复
阅读 2.1k
2 个回答
✓ 已被采纳

这个没难度啊
$i=0;
foreach ($arr as $key => $value) {

if(is_array($value['child'])){
    foreach ($value['child'] as $k => $v) {
        $array[$i]['id']=$v['id'];
        $array[$i]['cate_name']=$v['cate_name'];
        $array[$i]['parent_id']=$v['parent_id'];
        $i++;
    }
}

}
var_dump($array);

误杀小兵
  • 1
新手上路,请多包涵

$result = [];

function getChild($parentId, $child)
{

global $result;
foreach ($child as $item) {
   $result[] = [
        'id' =>$item['id'],
        'cate_name' => $item['cate_name'],
        'parent_id' => $parentId
    ];
    if ($item['child']) {
        getChild($item['id'], $item['child']);
    }
}

}

getChild(0, $arr);
var_dump($result);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏