Tags
Asked 2 years ago
9 Jun 2021
Views 221
jqueryLearner

jqueryLearner posted

How to flatten multi-dimensional array to single-dimensional in php ?

How to "flatten" a multi-dimensional array to one array in PHP ?
jaman

jaman
answered Apr 26 '23 00:00

You can flatten a multi-dimensional array into a single-dimensional array in PHP using recursion. Here's an example function that flattens a multi-dimensional array:



function flatten_array($array) {
    $result = array();
    foreach ($array as $value) {
        if (is_array($value)) {
            $result = array_merge($result, flatten_array($value));
        } else {
            $result[] = $value;
        }
    }
    return $result;
}

This function checks each value in the array to see if it's an array itself. If it is, it calls itself recursively on that sub-array. If it's not an array, it simply adds the value to the result array.

You can use this function like this:

php
Copy code
$multi_dim_array = array(array(1,2,3), array(4,5,6), array(7,8,9));
$single_dim_array = flatten_array($multi_dim_array);
print_r($single_dim_array);
This will output:


A

rray
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)

Note that this function will flatten any multi-dimensional array, regardless of its depth or structure.
Post Answer