Last Updated: February 25, 2016
·
1.164K
· nikkobautista

Recursive function for flattening arrays

/**
 * Flattens an array into a single dimension array
 * @param  array $array         Array to flatten
 * @param  string $parent       The parent indice
 * @param  string $separator    The separator used in between indices
 * @return array                Flattened array
 */
function flatten($array, $parent = '', $separator = '.')
    $return_array = array();
    foreach($array as $key => $value) {
        if( is_array($value) ) {
            $return_array = array_merge($return_array, flatten($value, $parent.$separator.$key, $separator));
        } else {
            $return_array[$parent.$separator.$key] = $value;
        }
    }
    return $return_array;
}