PHP: find same keys in multidimensional array and combine results

I have a multidimensional array that 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". After that, I would combine these two arrays into one. fe

$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 can understand my problem. Congratulated

+1


source to share


3 answers


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

      



See how it works

+8


source


you can just loop through the array and remove the corresponding 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]);
       }
    }

      

+1


source


You could just exclude 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'
        )
    )
)

      

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

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

      

+1


source







All Articles