Home > Backend Development > PHP Tutorial > How Can I Flatten a Multidimensional Array into a One-Dimensional Array in PHP?

How Can I Flatten a Multidimensional Array into a One-Dimensional Array in PHP?

Susan Sarandon
Release: 2024-12-04 06:08:14
Original
484 people have browsed it

How Can I Flatten a Multidimensional Array into a One-Dimensional Array in PHP?

Unflattening a Multidimensional Array into a One-Dimensional Array

The task of transforming a multidimensional array into a one-dimensional array can be accomplished with the array_reduce function. This function iteratively applies a provided reduction function to an array, accumulating a single result.

For the specific case of flattening a multidimensional array with simple numeric keys, we can leverage the array_merge function as the reduction function. This function takes two arrays and combines them into a single array.

Utilizing array_reduce with array_merge provides a straightforward method for unflattening a multidimensional array into a linear sequence of elements. As an example, consider the following multidimensional array:

$array = array(array('foo', 'bar', 'hello'), array('world', 'love'), array('stack', 'overflow', 'yep', 'man'));
Copy after login

Applying array_reduce($array, 'array_merge', array()) will yield the desired one-dimensional array:

array('foo', 'bar', 'hello', 'world', 'love', 'stack', 'overflow', 'yep', 'man')
Copy after login

This approach effectively collapses the nested structure of the multidimensional array, producing a flattened array suitable for further processing or storage.

The above is the detailed content of How Can I Flatten a Multidimensional Array into a One-Dimensional 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