How to flatten a 2D array into a sorted one-dimensional array in PHP

1 Answer

0 votes
function flattenAndSort2DArray($array2d) {
    $flattenedArray = [];
    
    // Flatten the 2D array
    foreach ($array2d as $subArray) {
        foreach ($subArray as $element) {
            $flattenedArray[] = $element;
        }
    }
    
    // Sort the flattened array
    sort($flattenedArray);
    
    return $flattenedArray;
}

$array2d = [
    [4, 5, 3],
    [30, 20],
    [10],
    [1, 2, 6, 7, 8],
];

$sortedArray = flattenAndSort2DArray($array2d);

echo implode(", ", $sortedArray);



/*
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30

*/

 



answered Aug 15, 2024 by avibootz
...