Tags
array
Asked 3 years ago
9 Jun 2021
Views 652
ruby-rails

ruby-rails posted

how to Convert multidimensional array into single array ?

how to Convert multidimensional array into single array ?
jqueryLearner

jqueryLearner
answered Apr 26 '23 00:00

To convert a multidimensional array into a single array in PHP, you can use the array_merge() function recursively. Here is an example:



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;
}

$multi_array = array(array('a', 'b'), array('c', 'd'), array('e', 'f', 'g'));
$single_array = flatten_array($multi_array);
print_r($single_array);

In this example, the flatten_array() function recursively calls itself to flatten the multidimensional array. The array_merge() function is used to merge the resulting arrays into a single array. The output of the code above will be:



Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
    [6] => g
)

As you can see, the multidimensional array has been flattened into a single-dimensional array.
Post Answer