📜  array flat php (1)

📅  最后修改于: 2023-12-03 14:59:23.082000             🧑  作者: Mango

PHP Array Flat

In PHP, an array can contain nested arrays, which can contain other nested arrays, creating a hierarchical structure. However, sometimes we need to flatten this array into a simple one-dimensional array. This is where the array_flat() function comes in handy.

Definition

The array_flat() function returns a one-dimensional array from a multi-dimensional array by flattening it.

function array_flat($array) {
    $result = [];

    foreach ($array as $value) {
        if (is_array($value)) {
            $result = array_merge($result, array_flat($value));
        } else {
            $result[] = $value;
        }
    }
    
    return $result;
}
Example Usage
$array = [1, 2, [3, 4, [5], 6], 7];

$flatArray = array_flat($array);

print_r($flatArray);

// Output:
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 4
//     [4] => 5
//     [5] => 6
//     [6] => 7
// )
Explanation

In the example above, we have a multi-dimensional array $array containing various nested arrays. We then pass this array to the array_flat() function, which recursively traverses each element of the array.

If the current element is an array, the array_flat() function calls itself to flatten that array as well. Once a one-dimensional array is created, the elements are merged with the $result array. If the element is not an array, we simply add it to the $result array.

Finally, the $result array, which now contains all the elements in a one-dimensional format, is returned.

Conclusion

The array_flat() function is a useful tool when working with multi-dimensional arrays in PHP. It allows you to flatten complex arrays into a simple, one-dimensional format, which can make manipulating data much easier.