PHP – Array flattern function

Łukasz Piotrowski Comments 0

    Hi!

    Today I needed small function to flattern my multidimensional array.
    It's not normal becouse it fetch all arrays with walues and put it into 2 dimensional array.


    Function

    function array_flatten($array, &$values)
    {
        if(empty($values))
            $values = [];
    
        $nonArrayValues = array();
        foreach ($array as $key => $value)
        {
            if(!is_array($value))
            {
                $nonArrayValues[$key] = $value;
            }
            else
            {
                $values[$key] = array_flatten($value, $values);
            }
        }
        return $nonArrayValues;
    }

    Example

    $arrayValues = [
        'val3.1' => 'valsss',
        'val3.2',
        'val3' => [
            'val3.1' => 'valsss',
            'val3.2',
            'val3.3' => [
                'val4.1',
                'val4' => ['vall'],
            ]
        ],
    ];
    
    $free = array_flatten($arrayValues, $newArrayValues);
    echo '<pre>'; print_r($newArrayValues); print_r($free); echo'</pre>';
    
    
    /*
    Array
    (
        [val4] => Array
        (
            [0] => vall
        )
        [val3.3] => Array
        (
            [0] => val4.1
        )
        [val3] => Array
        (
            [val3.1] => valsss
            [0] => val3.2
        )
    )
    Array
    (
        [val3.1] => valsss
        [0] => val3.2
    )
    *\

    Explanation

    array_flatten($arrayValues, $newArrayValues) have 2 parameters:
    $arrayValues Array of values
    $newArrayValues Output table

    Own function returns array of free values which are on root of Input array.

    Top