Home > Backend Development > PHP Tutorial > How Can I Efficiently Flatten a Multidimensional Numeric-Keyed Array in PHP?

How Can I Efficiently Flatten a Multidimensional Numeric-Keyed Array in PHP?

Susan Sarandon
Release: 2024-12-12 21:53:14
Original
272 people have browsed it

How Can I Efficiently Flatten a Multidimensional Numeric-Keyed Array in PHP?

Simplifying Multidimensional Arrays into Linear Structures

Converting multidimensional arrays into their one-dimensional counterparts can often be a daunting task, especially when dealing with arrays containing solely numeric keys. However, there is a simple yet elegant solution to flatten these structures, utilizing PHP's array functions.

Answer Explained

The solution employs the array_reduce() function in conjunction with array_merge(). array_reduce() iterates through each element of the array, applying a user-defined function to accumulate a final reduced value. In this case, we pass in the array_merge() function, which combines two arrays into a single array.

By specifying an empty array as the initial value of the reduce operation, we ensure that the final result is an array containing all the elements from the multidimensional array. Each iteration concatenates the current subarray with the accumulator, effectively flattening the input.

Example Implementation

Consider the multidimensional array provided in the question:

$array = [
    [0 => 'foo', 1 => 'bar', 2 => 'hello'],
    [0 => 'world', 1 => 'love'],
    [0 => 'stack', 1 => 'overflow', 2 => 'yep', 3 => 'man'],
];
Copy after login

To flatten this array, we can simply use the following code:

$result = array_reduce($array, 'array_merge', []);
Copy after login

This would produce the desired one-dimensional array:

$result = [
    'foo', 'bar', 'hello', 'world', 'love', 'stack', 'overflow', 'yep', 'man'
];
Copy after login

The above is the detailed content of How Can I Efficiently Flatten a Multidimensional Numeric-Keyed Array 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