<?php //////当前查询出来的数据 $redata = array( 0=>['id'=>1,'name'=>'张三','age'=>22,'hobby'=>'学习'], 1=>['id'=>1,'name'=>'张三','age'=>22,'hobby'=>'骑行'], 2=>['id'=>2,'name'=>'李四','age'=>20,'hobby'=>'旅游'], ); //如何才能转换成下面这种形式的? 写了一上午 愣是没写出来 $arr = array( 0=>[ 'id'=>1,'name'=>'张三','age'=>22,'hobby'=> ['学习', '骑行'] ], 1=>[ 'id'=>2,'name'=>'李四','age'=>20,'hobby'=> ['旅游'] ] );
不冷不热2018-08-24 14:41:56
$r = array( 0=>['id'=>1,'name'=>'张三','age'=>22,'hobby'=>'学习'], 1=>['id'=>1,'name'=>'张三','age'=>22,'hobby'=>'骑行'], 2=>['id'=>2,'name'=>'李四','age'=>20,'hobby'=>'旅游'], ); $dd = []; foreach ($r as $k => $vv) { $dd[$vv['id']]['id'] = $vv['id']; $dd[$vv['id']]['age'] = $vv['age']; $dd[$vv['id']]['hobby'][] = $vv['hobby']; } P($dd); Array ( [1] => Array ( [id] => 1 [age] => 22 [hobby] => Array ( [0] => 学习 [1] => 骑行 ) ) [2] => Array ( [id] => 2 [age] => 20 [hobby] => Array ( [0] => 旅游 ) ) )
不冷不热2018-08-24 14:40:49
$dd = []; foreach ($r as $k => $vv) { $dd[$vv['id']]['id'] = $vv['id']; $dd[$vv['id']]['age'] = $vv['age']; $dd[$vv['id']]['hobby'][] = $vv['hobby']; }
這樣