PHP针对二维数组无限遍历变形研究
一、需要变形的二维数组
1 $arr = Array( 2 Array 3 ( 4 'material_id' => 1, 5 'material_name' => '铜板纸', 6 'parent_id' => 0 7 ), 8 Array 9 ( 10 'material_id' => 26, 11 'material_name' => '哑粉纸', 12 'parent_id' => 0 13 ), 14 Array 15 ( 16 'material_id' => 61, 17 'material_name' => '胶版', 18 'parent_id' => 0 19 ), 20 Array 21 ( 22 'material_id' => 95, 23 'material_name' => '高级哑粉', 24 'parent_id' => 0 25 ), 26 Array 27 ( 28 'material_id' => 4, 29 'material_name' => '250g铜版纸', 30 'parent_id' => 1 31 ), 32 Array 33 ( 34 'material_id' => 5, 35 'material_name' => '200g铜版纸', 36 'parent_id' => 1 37 ), 38 Array 39 ( 40 'material_id' => 27, 41 'material_name' => '250g哑粉纸', 42 'parent_id' => 26 43 ), 44 45 Array 46 ( 47 'material_id' => 28, 48 'material_name' => '200g哑粉纸', 49 'parent_id' => 26 50 ), 51 Array 52 ( 53 'material_id' => 29, 54 'material_name' => '200g哑粉纸的子项', 55 'parent_id' => 28 56 ), 57 Array 58 ( 59 'material_id' => 30, 60 'material_name' => '200g哑粉纸的子项的子项', 61 'parent_id' => 29 62 ) 63 );
二、变形后的数组形式
1 array ( 2 0 => 3 array ( 4 'material_id' => 1, 5 'material_name' => '铜板纸', 6 'parent_id' => 0, 7 'children' => 8 array ( 9 0 => 10 array ( 11 'material_id' => 4, 12 'material_name' => '250g铜版纸', 13 'parent_id' => 1, 14 ), 15 1 => 16 array ( 17 'material_id' => 5, 18 'material_name' => '200g铜版纸', 19 'parent_id' => 1, 20 ), 21 ), 22 ), 23 1 => 24 array ( 25 'material_id' => 26, 26 'material_name' => '哑粉纸', 27 'parent_id' => 0, 28 'children' => 29 array ( 30 0 => 31 array ( 32 'material_id' => 27, 33 'material_name' => '250g哑粉纸', 34 'parent_id' => 26, 35 ), 36 1 => 37 array ( 38 'material_id' => 28, 39 'material_name' => '200g哑粉纸', 40 'parent_id' => 26, 41 'children' => 42 array ( 43 0 => 44 array ( 45 'material_id' => 29, 46 'material_name' => '200g哑粉纸的子项', 47 'parent_id' => 28, 48 'children' => 49 array ( 50 0 => 51 array ( 52 'material_id' => 30, 53 'material_name' => '200g哑粉纸的子项的子项', 54 'parent_id' => 29, 55 ), 56 ), 57 ), 58 ), 59 ), 60 ), 61 ), 62 2 => 63 array ( 64 'material_id' => 61, 65 'material_name' => '胶版', 66 'parent_id' => 0, 67 ), 68 3 => 69 array ( 70 'material_id' => 95, 71 'material_name' => '高级哑粉', 72 'parent_id' => 0, 73 ), 74 )
三、实现代码
1 public function ceshi($arr, &$arrParent = []) 2 { 3 // 首次获取parent_id = 0的相关父级项 4 foreach ($arr as $key => $val) { 5 if ($val['parent_id'] == 0) { 6 $arrParent[] = $val; 7 unset($arr[$key]); 8 } 9 } 10 11 foreach ($arrParent as $parentKey => $parent) { 12 foreach ($arr as $key => $val) { 13 if ($val['parent_id'] == $parent['material_id']) { 14 $arrParent[$parentKey]['children'][] = $val; 15 unset($arr[$key]); // 匹配完成则删除 16 $this->ceshi($arr, $arrParent[$parentKey]['children']); 17 } 18 } 19 } 20 21 return $arrParent; 22 }