技术相关 · 2015年5月7日

PHP根据数组某个键值相同合并数组

有时候我们需要将两个数组合并,并且将某些键值再次合并成一个数组。

想了很多方法,都不理想,最后百度看了一个不错的方法,在这里分享给大家。

<?php
$a=array(
	array("username"=>"piaoyudesi","email"=>"piaoyudesi@163.com","address"=>"shenzhen","item_id"=>"10058","item_title"=>"BPS8"),
	array("username"=>"huakai","email"=>"huakai@163.com","address"=>"zhongshan","item_id"=>"10087","item_title"=>"BPS9"),
	array("username"=>"huakai","email"=>"huakai@163.com","address"=>"zhongshan","item_id"=>"10047","item_title"=>"BPS10"),
	array("username"=>"piaoyudesi","email"=>"piaoyudesi@163.com","address"=>"shenzhen","item_id"=>"10042","item_title"=>"BPS10"),
	array("username"=>"jimowenxin","email"=>"jimowenxin@163.com","address"=>"zhuhai","item_id"=>"10031","item_title"=>"BPS18")
);
$u=array();
foreach($a as $k=>&$e){
	$name=&$e['username'];
	if(!isset($u[$name])){
		$u[$name]=$e;
		unset($u[$name]['item_id'],$u[$name]['item_title']);
	}
	$u[$name]['goods'][]=array('item_id'=>$e['item_id'],'item_title'=>$e['item_title']);
}
$a=array_values($u); unset($u);
print_r($a);
=========
Array
(
    [0] => Array
        (
            [username] => piaoyudesi
            [email] => piaoyudesi@163.com
            [address] => shenzhen
            [goods] => Array
                (
                    [0] => Array
                        (
                            [item_id] => 10058
                            [item_title] => BPS8
                        )

                    [1] => Array
                        (
                            [item_id] => 10042
                            [item_title] => BPS10
                        )
                )		 
        )				 
    [1] => Array
        (
            [username] => huakai
            [email] => huakai@163.com
            [address] => zhongshan
            [goods] => Array
                (
                    [0] => Array
                        (
                            [item_id] => 10087
                            [item_title] => BPS9
                        )

                    [1] => Array
                        (
                            [item_id] => 10047
                            [item_title] => BPS10
                        )
                )		 
        )				 
    [2] => Array
        (
            [username] => jimowenxin
            [email] => jimowenxin@163.com
            [address] => zhuhai
            [goods] => Array
                (
                    [0] => Array
                        (
                            [item_id] => 10031
                            [item_title] => BPS18
                        )
                )		 
        )				 
)