Turning Multidimensional Array into One-Dimensional Array

Convert multidimensional array into single array

Assuming this array may or may not be redundantly nested and you're unsure of how deep it goes, this should flatten it for you:

function array_flatten($array) { 
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}

How can I convert a multidimensional array into one level array?

It looks like you want all sub array values to be in the single array.

$singleArray = [];
foreach($multiarray as $array) {
$singleArray = array_merge($singleArray, array_values($array));
}

This may contain some values as a duplicate. To clean them up you can do

$uniqueValues = array_unique($singleArray);

How to convert multi-dimensional array into one-dimensional array in CLICKHOUSE

Use function arrayFlatten / flatten:

SELECT arrayFlatten([[1, 2, 3], [4, 5]])
/*
┌─arrayFlatten([[1, 2, 3], [4, 5]])─┐
│ [1,2,3,4,5] │
└───────────────────────────────────┘
*/

Convert array of single-element arrays to a one-dimensional array

For your limited use case, this'll do it:

$oneDimensionalArray = array_map('current', $twoDimensionalArray);

This can be more generalized for when the subarrays have many entries to this:

$oneDimensionalArray = call_user_func_array('array_merge', $twoDimensionalArray);


Related Topics



Leave a reply



Submit