Search code examples
phparraysarray-merge

php merge arrays of the same array


I have this array in php :

array:5 [
  0 => array:3 [
    "tab" => "9"
    "layout_id" => "11"
    "banners_ids" => "7"
  ]
  1 => array:3 [
    "tab" => "9"
    "layout_id" => "11"
    "banners_ids" => "8"
  ]
  2 => array:3 [
    "tab" => "10"
    "layout_id" => null
    "banners_ids" => null
  ]
  3 => array:3 [
    "tab" => "11"
    "layout_id" => null
    "banners_ids" => null
  ]
  4 => array:3 [
    "tab" => "12"
    "layout_id" => null
    "banners_ids" => null
  ]
]

And i need to merge in the same array those that have the same "tab" key to have something like this:

array:5 [
  0 => array:3 [
    "tab" => "9"
    "layout_id" => "11"
    "banners_ids" => "8,7"
  ]
  1 => array:3 [
    "tab" => "10"
    "layout_id" => null
    "banners_ids" => null
  ]
  2 => array:3 [
    "tab" => "11"
    "layout_id" => null
    "banners_ids" => null
  ]
  3 => array:3 [
    "tab" => "12"
    "layout_id" => null
    "banners_ids" => null
  ]
]

How can I reach this? I trie with a foreach and positions like current() or prev() but with no result.


Solution

  • Got distracted with things. Either use Bhaskar's answer or mine... Or combine them.

    <?php
    
    $array=json_decode('[{"tab":"9","layout_id":"11","banners_ids":"7"},{"tab":"9","layout_id":"11","banners_ids":"8"},{"tab":"10","layout_id":null,"banners_ids":null},{"tab":"11","layout_id":null,"banners_ids":null},{"tab":"12","layout_id":null,"banners_ids":null}]',true);
    
    
    //var_dump($array);
    $new_array=array();
    foreach($array as $entry)
    {
    $new_array[$entry['tab']]['tab']=$entry['tab'];
    $new_array[$entry['tab']]['layout_id']=$entry['layout_id'];
    $new_array[$entry['tab']]['banners_ids'][]=$entry['banners_ids'];
    }
    
    foreach($new_array as $key=>$val)
    {
    $new_array[$key]['banners_ids']=implode(',',$new_array[$key]['banners_ids']);
    }
    
    var_dump($new_array);