Created
January 12, 2016 12:55
-
-
Save mewm/44681f2e2a36f23a8c9c to your computer and use it in GitHub Desktop.
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 | |
$_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