Home > Backend Development > PHP Tutorial > How Can I Flatten Multidimensional Arrays in PHP?

How Can I Flatten Multidimensional Arrays in PHP?

Linda Hamilton
Release: 2025-01-05 09:31:39
Original
253 people have browsed it

How Can I Flatten Multidimensional Arrays in PHP?

PHP Flatten Multidimensional Arrays

flattening a multidimensional array into a single dimension can be essential for some data processing tasks. PHP offers a convenient way to perform this conversion using array manipulation functions.

Solution Using array_merge

$array = [
    [1, 2, 3],
    [4, 5, 6],
];

$result = call_user_func_array('array_merge', $array);

echo "<pre class="brush:php;toolbar:false">";
print_r($result); // Output: [1, 2, 3, 4, 5, 6]
Copy after login

The call_user_func_array() function allows you to pass an array of arguments to a function. In this case, we use it to call the array_merge() function with each element of the multidimensional array as an argument.

Solution Using Recursive Function

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

$array = [
    [1, 2, 3],
    [4, 5, 6],
];

$result = array_flatten($array);

echo "<pre class="brush:php;toolbar:false">";
print_r($result); // Output: [1, 2, 3, 4, 5, 6]
Copy after login

This recursive function works by iterating through the array and recursively calling itself on any array elements it encounters. It merges the results from each recursive call into the final flattened array.

The above is the detailed content of How Can I Flatten Multidimensional Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template