时间:2021-07-01 10:21:17 帮助过:3人阅读
目前有个层次结构不规则的多维数组,需要转换成二维数组,还请请教各位大虾。
源数据如下。
$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;
}
}