原始阵列:
$cat = Array (
[0] => Array ( [id] => 2 [name] => W [pid] => 1 )
[1] => Array ( [id] => 4 [name] => M [pid] => 1 )
[2] => Array ( [id] => 5 [name] => C [pid] => 1 )
[3] => Array ( [id] => 8 [name] => K [pid] => 7 )
[4] => Array ( [id] => 9 [name] => B [pid] => 7 )
[5] => Array ( [id] => 12 [name] => X [pid] => 11 )
)
我想得到这样的结果:
$cat = Array (
[0] => Array (
[pid]=>1,
[item] => Array(
[0] => Array ( [id] => 2 [name] => W ),
[1] => Array ( [id] => 4 [name] => M ),
[2] => Array ( [id] => 5 [name] => C )
)
),
[1] => Array (
[pid]=>7,
[item]=>Array(
[0] => Array ( [id] => 8 [name] => K ),
[0] => Array ( [id] => 9 [name] => B )
)
),
[2] => Array (
[pid]=>11,
[item]=>Array(
[0] => Array ( [id] => 12 [name] => X )
)
)
)
如何?
答案 0 :(得分:0)
$newCat = array();
array_walk($cat, function($v) use(&$newCat){
$i = $v['pid'];
unset($v['pid']);
if(!isset($newCat[$i]))
$newCat[$i] = array('pid' => $i, 'item' => array());
$newCat[$i]['item'][] = $v;
});
print_r( array_values($newCat) );