例如有一个二维数组 $arr:
$arr = array( array( 'review_id' =>102 , 'url'=>'a.jpg', ), array( 'review_id' =>102 , 'url'=>'b.jpg', ), array( 'review_id' =>102 , 'url'=>'c.jpg', ), array( 'review_id' =>103 , 'url'=>'aa.jpg', ), array( 'review_id' =>103 , 'url'=>'bb.jpg', ), array( 'review_id' =>104 , 'url'=>'aaa.jpg', ), array( 'review_id' =>105 , 'url'=>null, ), array( 'review_id' =>106 , 'url'=>null, ), );
现在需要把相同 review_id 的数组的 url 进行合并,形成:
Array ( [0] => Array ( [review_id] => 102 [url] => Array ( [0] => a.jpg [1] => b.jpg [2] => c.jpg ) ) [1] => Array ( [review_id] => 103 [url] => Array ( [0] => aa.jpg [1] => bb.jpg ) ) [2] => Array ( [review_id] => 104 [url] => aaa.jpg ) [3] => Array ( [review_id] => 105 [url] => ) [4] => Array ( [review_id] => 106 [url] => ) )
===
程序:
<?php $arr = array( array( 'review_id' =>102 , 'url'=>'a.jpg', ), array( 'review_id' =>102 , 'url'=>'b.jpg', ), array( 'review_id' =>102 , 'url'=>'c.jpg', ), array( 'review_id' =>103 , 'url'=>'aa.jpg', ), array( 'review_id' =>103 , 'url'=>'bb.jpg', ), array( 'review_id' =>104 , 'url'=>'aaa.jpg', ), array( 'review_id' =>105 , 'url'=>null, ), array( 'review_id' =>106 , 'url'=>null, ), ); $res = array(); foreach($arr as $item) { if(! isset($res[$item['review_id']])){ $res[$item['review_id']] = $item; }else{ $res[$item['review_id']]['url'] .= ',' . $item['url']; //[url] => a.jpg,b.jpg,c.jpg } } $res = array_values($res); $a = array(); foreach ($res as $k => $v) { if($v['url'] != "" && strpos($v['url'],",") !== false){ $a = explode(",", $res[$k]['url']); $res[$k]['url'] = $a; } } echo "<pre>"; print_r($res); echo "</pre>";