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"
]
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.
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 .
This single line would do that: $array = array_column($array, 'plan'); The first argument is an array | The second argument is an array key.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With