PHP:在多维数组中找到相同的键并合并结果

时间:2012-01-12 17:45:00

标签: php multidimensional-array

我有一个多维数组,如下所示:

$array = (
    [0] => array (
        ['WS'] => array(
             [id] => 2,
             [name] => 'hello'
             )
        )
    ), 
    [1] => array (
        ['SS'] => array(
             [id] => 1,
             [name] => 'hello2'
             )
        )
    ),
    [2] => array (
        ['WS'] => array(
             [id] => 5,
             [name] => 'helloAGAIN'
             )
        )
)

如您所见,$ array [0]和$ array [2]具有相同的密钥[WS]。我需要一个函数来找到那些“相同的键”。然后我将这两个数组合并为一个。 f.e。

$array =
(
    [0] => array 
        (
            ['WS'] => array
                (
                     [0] => array
                         (
                             [id] => 2,
                             [name] => 'hello'
                         ),
                     [1] => array
                         (
                            [id] => 5,
                            [name] => 'helloAGAIN'
                         )
                )
        ),
    [1] => array 
         (
             ['SS'] => array
                 (
                     [0] => array
                         (
                              [id] => 1,
                              [name] => 'hello2'
                         )
                 )
         )
    )

希望你们明白我的问题。 招呼

3 个答案:

答案 0 :(得分:8)

function group_by_key ($array) {
  $result = array();
  foreach ($array as $sub) {
    foreach ($sub as $k => $v) {
      $result[$k][] = $v;
    }
  }
  return $result;
}

See it working

答案 1 :(得分:1)

你可以循环遍历数组并删除匹配的元素

    $multiArray = array('0' => etc etc);
    $matches = array();

    foreach(multiArray as $key => $val)
    {
       $keyValToCheck = key($val);

       if(!in_array($keyValToCheck, $matches))
       {
          $matches[] = $keyValToCheck; // add value to array matches

          // remove item from array because match has been found
          unset($multiArray[$key][$keyValToCheck]);
       }
    }

答案 2 :(得分:1)

您可以简单地消除数组的第一级,最终会得到类似的结果:

$array = (
    ['WS'] => array(
        [0] => array(
                [id] => 2,
                [name] => 'hello'
        ),
        [1] => array(
               [id] => 5,
               [name] => 'helloAGAIN'
        )
    ),
    ['SS'] => array(
        [0] => array(
              [id] => 1,
              [name] => 'hello2'
        )
    )
)

这样你可以像这样添加数组:

$array['WS'][] = array();