Skip to content

Instantly share code, notes, and snippets.

@HavenShen
Created May 17, 2018 02:56
Show Gist options
  • Save HavenShen/46b31395122d4f56213b0de740b61da9 to your computer and use it in GitHub Desktop.
Save HavenShen/46b31395122d4f56213b0de740b61da9 to your computer and use it in GitHub Desktop.
Flattening a PHP multidimensional array.
<?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