Wednesday, 10 August 2016

Convert multidimensional array to single dimensional using php


Below is the function to convert multidimensional array into single dimensional array.



function array_flatten($array, $x = NULL) {

        if (!is_array($array)) {
            return false;
        }
        $result = array();

        $x = ($x == '') ? 0 : $x;

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $result = array_merge($result, self::array_flatten($value, $x++));
            } else {
                $result[$x][$key] = $value;
            }
        }
        return $result;

    }