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

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 个回答
✓ 已被采纳

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

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