Skip to content

Instantly share code, notes, and snippets.

@techslides
Created May 17, 2016 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techslides/0bf465741c29d2033e1ce257ff1f006b to your computer and use it in GitHub Desktop.
Save techslides/0bf465741c29d2033e1ce257ff1f006b to your computer and use it in GitHub Desktop.
Flattening Arrays with PHP
<?php
//Good Article: http://www.cowburn.info/2012/03/17/flattening-a-multidimensional-array-in-php/
//Exmaple: http://www.tehplayground.com/#9zwqvG1XM
$aa = array("first name"=>"john","last name"=>"smith","more data"=>array("age"=>"12","role"=>"manager"),"gender"=>"male");
//flatten with keys
$output = iterator_to_array(new RecursiveIteratorIterator(
new RecursiveArrayIterator($aa)), TRUE);
print_r($output);
//flatten without keys
$output = iterator_to_array(new RecursiveIteratorIterator(
new RecursiveArrayIterator($aa)), FALSE);
print_r($output);
//pull out keys and values seperately via walking recursive
$keys=array();
$values=array();
array_walk_recursive($aa, function ($item, $key) use (&$keys,&$values) {
//echo "$key holds $item\n";
$keys[] = $key;
$values[] = '"'.$item.'"';
});
print_r($keys);
print_r($values);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment