PHP: find same keys in a multidimensional-array and merge the findings

廉价感情. 提交于 2020-01-11 12:32:49

问题


I have a multidimensional-array which looks like this:

$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'
             )
        )
)

As you can see, $array[0] and $array[2] have the same key [WS]. I need a function to find those "same keys". Afterthat I would merge these two arrays into one. 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'
                         )
                 )
         )
    )

Hope you guys understand my problem. greets


回答1:


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

See it working




回答2:


you can just loop through the array and delete matching elements

    $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]);
       }
    }



回答3:


You could simply eliminate the first level of your array and you would end up with something like this:

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

That way you can add things to your array like this:

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


来源:https://stackoverflow.com/questions/8839697/php-find-same-keys-in-a-multidimensional-array-and-merge-the-findings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!