<tutorialjinni.com/>

PHP Flatten Multidimensional Array with Keys

Posted Under: PHP, Snippets on Aug 19, 2018
This simple snippet can flatten a multi dimensional Array and keep the keys intact.
$multidimensionalArray = array(
  array(
    'name'  => 'Test 1',
    'slug'  => 'test-1'
  ),
  array(
    'name'  => 'Foo1',
    'slug'  => 'Bar1'
  ),
  array(
    'name'  => 'Foo2',
    'slug'  => 'Bar2'
  ),
  array(
    'name'  => 'Test 2',
    'slug'  => 'test-2'
  ),
  array(
    'name'  => 'Test 3',
    'slug'  => 'test-3'
  ),
  array(
    'name'  => 'Test 4',
    'slug'  => 'test-4'
  ),
);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($multidimensionalArray));
foreach($it as $key=>$value) {
  echo "$key => $value n";
}

Output

name => Test 1 
slug => test-1 
name => Foo1 
slug => Bar1 
name => Foo2 
slug => Bar2 
name => Test 2 
slug => test-2 
name => Test 3 
slug => test-3 
name => Test 4 
slug => test-4 


imgae