Created
May 17, 2016 17:39
-
-
Save techslides/0bf465741c29d2033e1ce257ff1f006b to your computer and use it in GitHub Desktop.
Flattening Arrays with PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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