Skip to content

Instantly share code, notes, and snippets.

@arvindsvt
Forked from SeanCannon/array_flatten.php
Last active February 5, 2018 15:12
Show Gist options
  • Save arvindsvt/9923b4978fadbb81f0d81dfdbffad11b to your computer and use it in GitHub Desktop.
Save arvindsvt/9923b4978fadbb81f0d81dfdbffad11b to your computer and use it in GitHub Desktop.
PHP array_flatten() function. Convert a multi-dimensional array into a single-dimensional array.
<?php function array_flatten($array, $prefix = '') {
$result = array();
foreach($array as $key=>$value) {
if(is_array($value)) {
$result = $result + array_flatten($value, $prefix . $key . '.');
}
else {
$result[$prefix.$key] = $value;
}
}
return $result;
}
<?php
/**
* Convert a multi-dimensional array into a single-dimensional array.
* @param array $array The multi-dimensional array.
* @return array
*/
function array_flatten($array) {
if (!is_array($array)) {
return false;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
} else {
$result[$key] = $value;
}
}
return $result;
}
Using Standard PHP Library
$itcArray = array('a', 'b', array('c','d', array('e', 'f', 'g'), 'h'), 'i');
$itcIterate = new RecursiveIteratorIterator(new RecursiveArrayIterator($itcArray));
foreach($itcIterate as $result) {
echo $result. " ";
}
Using array_walk_recursive
function flatten(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
$itcArray = array('a', 'b', array('c','d', array('e', 'f', 'g'), 'h'), 'i');
$result = flatten($itcArray);
echo "<pre>";
print_r($result);
echo "</pre>";
Using Stack
function flatten(array $array) {
$flat = array(); // initialize an array
$stack = array_values($array); // initialize stack
while($stack) { // process the stack until finish
$value = array_shift($stack);
if (is_array($value)) { // a value to further process
$stack = array_merge(array_values($value), $stack);
}
else { // a value to take
if(!empty($value)) {
$flat[] = $value
}
}
}
return $flat;
}
$itcArray = array('a', 'b', array('c','d', array('e', 'f', 'g'), 'h'), 'i');
$result = flatten($itcArray);
echo "<pre>";
print_r($result);
echo "</pre>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment