Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multidimensional array to flatten WITH KEYS

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"
]
like image 335
Robert W. Hunter Avatar asked Feb 09 '16 14:02

Robert W. Hunter


People also ask

How do you flat a multidimensional array?

To flatten an array means to reduce the dimensionality of an array. In simpler terms, it means reducing a multidimensional array to a specific dimension. let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]]; and we need to return a new flat array with all the elements of the nested arrays in their original order.

How do you flatten an array in PHP?

Flattening a two-dimensional arrayarray_merge(... $twoDimensionalArray); array_merge takes a variable list of arrays as arguments and merges them all into one array. By using the splat operator ( ... ), every element of the two-dimensional array gets passed as an argument to array_merge .

How can I create a multidimensional array to a single array in PHP?

This single line would do that: $array = array_column($array, 'plan'); The first argument is an array | The second argument is an array key.


1 Answers

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));
like image 100
Steve Avatar answered Oct 22 '22 10:10

Steve