一、需要变形的二维数组
$arr = Array(
Array
(
'material_id' => 1,
'material_name' => '铜板纸',
'parent_id' => 0
),
Array
(
'material_id' => 26,
'material_name' => '哑粉纸',
'parent_id' => 0
),
Array
(
'material_id' => 61,
'material_name' => '胶版',
'parent_id' => 0
),
Array
(
'material_id' => 95,
'material_name' => '高级哑粉',
'parent_id' => 0
),
Array
(
'material_id' => 4,
'material_name' => '250g铜版纸',
'parent_id' => 1
),
Array
(
'material_id' => 5,
'material_name' => '200g铜版纸',
'parent_id' => 1
),
Array
(
'material_id' => 27,
'material_name' => '250g哑粉纸',
'parent_id' => 26
), Array
(
'material_id' => 28,
'material_name' => '200g哑粉纸',
'parent_id' => 26
),
Array
(
'material_id' => 29,
'material_name' => '200g哑粉纸的子项',
'parent_id' => 28
),
Array
(
'material_id' => 30,
'material_name' => '200g哑粉纸的子项的子项',
'parent_id' => 29
)
);
二、变形后的数组形式
array (
0 =>
array (
'material_id' => 1,
'material_name' => '铜板纸',
'parent_id' => 0,
'children' =>
array (
0 =>
array (
'material_id' => 4,
'material_name' => '250g铜版纸',
'parent_id' => 1,
),
1 =>
array (
'material_id' => 5,
'material_name' => '200g铜版纸',
'parent_id' => 1,
),
),
),
1 =>
array (
'material_id' => 26,
'material_name' => '哑粉纸',
'parent_id' => 0,
'children' =>
array (
0 =>
array (
'material_id' => 27,
'material_name' => '250g哑粉纸',
'parent_id' => 26,
),
1 =>
array (
'material_id' => 28,
'material_name' => '200g哑粉纸',
'parent_id' => 26,
'children' =>
array (
0 =>
array (
'material_id' => 29,
'material_name' => '200g哑粉纸的子项',
'parent_id' => 28,
'children' =>
array (
0 =>
array (
'material_id' => 30,
'material_name' => '200g哑粉纸的子项的子项',
'parent_id' => 29,
),
),
),
),
),
),
),
2 =>
array (
'material_id' => 61,
'material_name' => '胶版',
'parent_id' => 0,
),
3 =>
array (
'material_id' => 95,
'material_name' => '高级哑粉',
'parent_id' => 0,
),
)
三、实现代码
public function ceshi($arr, &$arrParent = [])
{
// 首次获取parent_id = 0的相关父级项
foreach ($arr as $key => $val) {
if ($val['parent_id'] == 0) {
$arrParent[] = $val;
unset($arr[$key]);
}
} foreach ($arrParent as $parentKey => $parent) {
foreach ($arr as $key => $val) {
if ($val['parent_id'] == $parent['material_id']) {
$arrParent[$parentKey]['children'][] = $val;
unset($arr[$key]); // 匹配完成则删除
$this->ceshi($arr, $arrParent[$parentKey]['children']);
}
}
} return $arrParent;
}