目前有個階層不規則的多維陣列,需要轉換成二維數組,還請請教各位大蝦。
來源資料如下。
$a = Array('0' => Array( 'id' => '125','level' => '0','child' => Array( '0' => Array('id' => '189' ,'level' => '1','child' => Array( '0' => Array( 'id' => '425', 'level' => '2','child' => Array( '0' => Array( 'id' => '385', 'level' => '3' ), '1' => Array( 'id' => '782', 'level' => '3' ), ), ), ), ), '1' => Array('id' => '688','level' => '1'),),),);
上述格式的數組結構層次較多,看起來比較亂,如果通過chrome配合phpview外掛程式查看的話,結構是這樣的。
Array('0' => Array('id' => '125','level' => '0','parent_id'='0'),'1' => Array('id' => '189','level' => '1','parent_id'='125'),'2' => Array('id' => '425','level' => '2','parent_id'='189'),'3' => Array('id' => '385','level' => '3','parent_id'='425'), '4' => Array('id' => '782','level' => '3','parent_id'='425'), '5' => Array('id' => '688','level' => '1','parent_id'='125'));
這裡的每個parent_id是上層數組的id,第一層的parent_id是0
回複內容:
目前有個階層不規則的多維陣列,需要轉換成二維數組,還請請教各位大蝦。
來源資料如下。
$a = Array('0' => Array( 'id' => '125','level' => '0','child' => Array( '0' => Array('id' => '189' ,'level' => '1','child' => Array( '0' => Array( 'id' => '425', 'level' => '2','child' => Array( '0' => Array( 'id' => '385', 'level' => '3' ), '1' => Array( 'id' => '782', 'level' => '3' ), ), ), ), ), '1' => Array('id' => '688','level' => '1'),),),);
上述格式的數組結構層次較多,看起來比較亂,如果通過chrome配合phpview外掛程式查看的話,結構是這樣的。
Array('0' => Array('id' => '125','level' => '0','parent_id'='0'),'1' => Array('id' => '189','level' => '1','parent_id'='125'),'2' => Array('id' => '425','level' => '2','parent_id'='189'),'3' => Array('id' => '385','level' => '3','parent_id'='425'), '4' => Array('id' => '782','level' => '3','parent_id'='425'), '5' => Array('id' => '688','level' => '1','parent_id'='125'));
這裡的每個parent_id是上層數組的id,第一層的parent_id是0
做個遞迴處理吧
function reformat($arrTmp, $parent_id=0, &$ret=null) { foreach($arrTmp as $k => $v) { $ret[$v['id']] = array('id'=>$v['id'], 'level'=>$v['level'], 'parent_id'=>$parent_id); if($v['child']) { reformat($v['child'], $v['id'], $ret); } } return $ret;}var_dump(reformat($a));
不客氣
class Test{ public function reduce_arr ($arr) { static $temp = array(); // 聲明了一個靜態局部變數 foreach ($arr as $key => $val) { if (is_array($val)) { $this->reduce_arr($val); } else { $temp[$key] = $val; } } return $temp; }}