如何简化这个多维关联数组?

时间:2015-05-06 16:54:28

标签: php arrays

$arr1 = array(

1=>array(
    'name' => 'a',
    'phone'=> '110',
),
2=>array(
    'name' => 'b',
    'phone'=> '119',
),
3=>array(
    'name' => 'a',
    'phone'=> '119',
 ),
4=>array(
    'name' => 'b',
    'phone'=> '110',
),
);

我花了3个小时搞清楚,并且失败。我想根据名称键值将手机值合并到新阵列。结果如下

$arr2 = array(
    1=>array(
        'name' => 'a',
        'phone'=> array(
           1=>'110',
           2=>'119',
        ),
    ),
    2=>array(
        'name' => 'b',
        'phone'=> array(
            1=>'110',
            2=>'119',
         ),
    )
);

它并不像看起来那么容易。

2 个答案:

答案 0 :(得分:6)

你需要循环遍历数组并创建一个新数组。

  

<?php

/** store the results in here **/
$targetArray = [];

/** the data source **/
$sourceArray = [
    1 => [
        'name' => 'a',
        'phone'=> '110',
    ],
    2 => [
        'name' => 'b',
        'phone'=> '119',
    ],
    3 => [
        'name' => 'a',
        'phone'=> '119',
    ],
    4 => [
        'name' => 'b',
        'phone'=> '110',
    ]
];

foreach($sourceArray as $arr) {
    /** create key based off name **/
    $targetArray[$arr['name']]['name'] = $arr['name'];
    /** add phone numbers as they are found **/
    $targetArray[$arr['name']]['phone'][] = $arr['phone'];
}

/** reindex the array **/
$targetArray = array_values($targetArray);

/** see the result **/
var_dump($targetArray);
  

输出

array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(1) "a"
    ["phone"]=>
    array(2) {
      [0]=>
      string(3) "110"
      [1]=>
      string(3) "119"
    }
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(1) "b"
    ["phone"]=>
    array(2) {
      [0]=>
      string(3) "119"
      [1]=>
      string(3) "110"
    }
  }
}

答案 1 :(得分:1)

这是一个解决方案:

// Use name as key to merge contact info.
foreach($arr1 as $contactInfo)
{
    $arr2[$contactInfo['name']]['name'] = $contactInfo['name'];
    $arr2[$contactInfo['name']]['phone'][] = $contactInfo['phone'];
}

// Go back to numeric indexes.
$arr2 = array_values($arr2);