Search code examples
phparraysrecursionmultidimensional-array

Get all values and associative keys as a flat array from a multidimensional array of variable depth/structure


Is there any way to flatten a multidimensional (1 to 3 levels max) with keys?

I have an array like this

array(
    'Orange',
    'Grape',
    'Banana' => array(
        'Big',
        'Small'
    ),
    'Apple' => array(
        'Red',
        'Green' => array(
            'Soft',
            'Hard'
        )
    )
);

And I want it to be like this

array(
    'Orange',
    'Grape',
    'Banana',
    'Big',
    'Small',
    'Apple',
    'Red',
    'Green',
    'Soft',
    'Hard'
);

So it will keep the order of appearance in order to lately get indexes with array_keys.

I've tried several ways but if the array elements a key for a new array, it wont be flattened, just skipped, so my final array looks like this

array:7 [▼
  0 => "Orange"
  1 => "Grape"
  2 => "Big"
  3 => "Small"
  4 => "Red"
  5 => "Soft"
  6 => "Hard"
]

Solution

  • You can write a recursive function for that:

    $nested = array(
        'Orange',
        'Grape',
        'Banana' => array(
            'Big',
            'Small'
        ),
        'Apple' => array(
            'Red',
            'Green' => array(
                'Soft',
                'Hard'
            )
        )
    );
    
    function flattern($array)
    {
        $flat=[];
        foreach($array as $key=>$val){
            if(is_array($val)){
                $flat[]=$key;
                $flat = array_merge($flat, flattern($val));
            }else{
                $flat[]=$val;
            }
        }
        return $flat;
    }
    
    var_dump(flattern($nested));