合并多维数组的数据

时间:2011-08-12 14:29:15

标签: php multidimensional-array

我有这种数组

Array ( [0] => Array (  [id] => 1 
                        [name] => PeopleOne
                        [address] => AddressOneOfPeopleOne 

        [1] => Array (  [id] => 2 
                        [name] => PeopleTwo 
                        [address] => AddressOneOfPeopleTwo 

        [2] => Array (  [id] => 3 
                        [name] => PeopleThree 
                        [address] => AddressOneOfPeopleThree 

        [3] => Array (  [id] => 4 
                        [name] => PeopleOne
                        [address] => AddressTwoOfPeopleOne 

我想要这种格式

Array ( [0] => Array (  [id] => 1 
                        [name] => PeopleOne
                        [address] => Array(
                                    [0] => AddressOneOfPeopleOne
                                    [1] => AddressTwoOfPeopleOne
                        )

        [1] => Array (  [id] => 2 
                        [name] => PeopleTwo 
                        [address] => AddressOneOfPeopleTwo 

        [2] => Array (  [id] => 3 
                        [name] => PeopleThree 
                        [address] => AddressOneOfPeopleThree 

我不知道该怎么办? 有人可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

我有一种感觉,这不是你想要的,但我不完全确定最终阵列中需要什么。这是怎么回事,至少从一开始呢?

<?php
$array = array(
array('id' => 1, 'name' => 'PeopleOne', 'address' => 'Address1'),
array('id' => 2, 'name' => 'PeopleTwo', 'address' => 'Address2'),
array('id' => 3, 'name' => 'PeopleOne', 'address' => 'Address3')
);


foreach ($array as $k => $v) {
$newarray[$v['name']][] = $v['address'];
}

echo '<pre>'.print_r($array,1).'</pre>';
echo '<pre>'.print_r($newarray,1).'</pre>';

?>

答案 1 :(得分:0)

我假设您的数组名为$ array。

foreach ($array as $subArray) {
    if (!is_array($subArray['address']) {
        $subArray['address'] = array($subArray['adress']);
    }
    $subArray['address'][] = 'AddressTwoOfPeopleOne';
}