Created
June 10, 2022 12:21
-
-
Save aaronsummers/4a971298ee78aaea3b4d34ffb4a246ec to your computer and use it in GitHub Desktop.
Flatten Multidimentional Arrays in PHP
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 | |
function array_flatten($arrays) { | |
if ( !is_array($arrays) ) | |
{ | |
return false; | |
} | |
$result = array(); | |
foreach ( $arrays as $key => $value ) | |
{ | |
if ( is_array($value) ) | |
{ | |
$result = array_merge( $result, array_flatten($value) ); | |
} | |
else | |
{ | |
$result[$key] = $value; | |
} | |
} | |
return $result; | |
} | |
// Example | |
$array = array( | |
'a' => 'letter', | |
'b' => array( | |
'b1' => 'bb', | |
'b2' => 'bb', | |
'b3' => array( | |
'bb1' => 'bbb' | |
) | |
) | |
); | |
// array_flatten($array) | |
echo '<pre>' . var_export(array_flatten($array), true) . '</pre>'; | |
// Return | |
array ( | |
'a' => 'letter', | |
'b1' => 'bb', | |
'b2' => 'bb', | |
'bb1' => 'bbb', | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment