我想合并具有一个唯一值的数组,如id和其他不同的值和键也

时间:2017-11-25 05:21:53

标签: php arrays

    Array(
        [0] => Array(
            [billing_first_name] => pp
            [user_id] => 1
        )
        [1] => Array(
            [billing_last_name] => pp
            [user_id] => 1
        )
        [2] => Array(
            [billing_city] => Nagpur
            [user_id] => 1
        )
        [3] => Array(
            [billing_first_name] => gaurav
            [user_id] => 6
        )
        [4] => Array(
            [billing_last_name] => bokade
            [user_id] => 6
        )
    )

我希望结果为:

    Array(
        [0] => Array(
            [user_id] => 1
            [billing_first_name] => pp
            [billing_last_name] => pp
            [billing_city] => Nagpur
        )
        [1] => Array(
            [user_id] => 6
            [billing_first_name] => gaurav
            [billing_last_name] => bokade
            [billing_city] => 
        )
    )

1 个答案:

答案 0 :(得分:0)

<?php
    $array = array(
                array('billing_first_name' => 'pp','user_id' => 1),
                array('billing_last_name' => 'pp','user_id' => 1),
                array('billing_city' => 'Nagpur','user_id' => 1),
                array('billing_first_name' => 'gaurav','user_id' => 6),
                array('billing_last_name' => 'bokade','user_id' => 6)
            );

    foreach($array as $r){
        foreach($r as $key => $s){
            $new[$r['user_id']][$key] = $s;
        }
    }
    echo "<pre>";print_r($new);
?>

结果

Array
(
    [1] => Array
        (
            [billing_first_name] => pp
            [user_id] => 1
            [billing_last_name] => pp
            [billing_city] => Nagpur
        )

    [6] => Array
        (
            [billing_first_name] => gaurav
            [user_id] => 6
            [billing_last_name] => bokade
        )

)