Created
May 17, 2018 02:56
-
-
Save HavenShen/46b31395122d4f56213b0de740b61da9 to your computer and use it in GitHub Desktop.
Flattening a PHP multidimensional array.
This file contains 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 | |
$array = [ | |
'personal' => [ | |
'name' => 'Haven Shen', | |
'age' => 18, | |
], | |
'gift' => [ | |
'name' => 'car', | |
'key' => [ | |
'more' | |
] | |
], | |
'money' => [ | |
'card' => 10000000.00 | |
], | |
'more' | |
]; | |
function flatten_array(array $items, array $flattened = []) { | |
foreach ($items as $item) { | |
if (is_array($item)) { | |
$flattened = flatten_array($item, $flattened); | |
continue; | |
} | |
$flattened[] = $item; | |
} | |
return $flattened; | |
} | |
var_dump(flatten_array($array)); | |
$flattened = iterator_to_array(new RecursiveIteratorIterator( | |
new RecursiveArrayIterator($array) | |
), false); | |
var_dump($flattened); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment