Home > database >  Merge Multiple Multidimensional Array from foreach
Merge Multiple Multidimensional Array from foreach

Time:09-09

I need to join these multidimensional arrays. I tried to use array_merge but it didn't work.

0: {
   0: {
      id: "121",
      slug: "btm-dc-402",
     },
   1: {
      id: "122",
      slug: "btm-dc-403",
      }
},
1: {
   0: {
      id: "493",
      slug: "jog-buah-401",
      },
   1: {
      id: "946",
      slug: "dps-buah-356",
      }
   }

Result that I expected like this.

   0: {
      id: "121",
      slug: "btm-dc-402",
     },
   1: {
      id: "122",
      slug: "btm-dc-403",
      }
   2: {
      id: "493",
      slug: "jog-buah-401",
      },
   3: {
      id: "946",
      slug: "dps-buah-356",
      }
   }

Could you please help. Thank you

CodePudding user response:

hint : to flatten an array use : array_walk_recursive

CodePudding user response:

<?php
    
$my_array = array(    
    0 => array(
        array(  
            "id"   => "121",  
            "slug"   => "btm-dc-402"  
        ),  
        array(  
            "id"   => "122",  
            "slug"   => "btm-dc-403"  
        ),  
    ),
    1 => array(
        array(  
            "id"   => "493",  
            "slug"   => "jog-buah-401"  
        ),  
        array(  
            "id"   => "946",  
            "slug"   => "dps-buah-356k"  
        ),    
    ),
);


$newArray = [];

foreach ($my_array as $key => $value) {
    foreach($value as $k => $v) {
        $newArray[] = $v;
    }
}

print_r($newArray);

Demo - https://3v4l.org/D2pC0

  • Related