Skip to content

Instantly share code, notes, and snippets.

@mewm
Created January 12, 2016 12:55
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 mewm/44681f2e2a36f23a8c9c to your computer and use it in GitHub Desktop.
Save mewm/44681f2e2a36f23a8c9c to your computer and use it in GitHub Desktop.
<?php
$_flatArray = [];
$_nestedArray = [
[
'id' => 1,
'name' => 'A',
'subcategories' => [
[
'id' => 2,
'name' => 'B',
'subcategories' => []
],
[
'id' => 3,
'name' => 'C',
'subcategories' => [
[
'id' => 31,
'name' => 'CA',
'subcategories' => []
],
[
'id' => 32,
'name' => 'CB',
'subcategories' => [
[
'id' => 321,
'name' => 'CBA',
'subcategories' => []
],
]
],
]
],
[
'id' => 4,
'name' => 'D',
'subcategories' => []
],
[
'id' => 5,
'name' => 'F',
'subcategories' => []
],
]
]
];
/**
* @author Dennis Micky Jensen <dj@miinto.com>
*
* @param array $nestedArray
* @param array $flattenedArray
*
* @return array
*/
function flattenArray(array $nestedArray, &$flattenedArray = [])
{
foreach($nestedArray as $subcategory) {
$_orphan = $subcategory;
unset($_orphan['subcategories']);
$flattenedArray[] = $_orphan;
if(!empty($subcategory['subcategories'])) {
flattenArray($subcategory['subcategories'], $flattenedArray);
}
}
return $flattenedArray;
}
print '<pre>';
print_r(flattenArray($_nestedArray));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment