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

发布于 2022-09-06 09:44:11 字数 1330 浏览 39 评论 0

$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",],//顶级分类
];

求大神们帮忙。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尹雨沫 2022-09-13 09:44:11

这个没难度啊
$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);

我要还你自由 2022-09-13 09:44:11

$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);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文