Home > Backend Development > PHP Tutorial > How to Flatten a Multidimensional Array in PHP?

How to Flatten a Multidimensional Array in PHP?

Patricia Arquette
Release: 2024-12-05 15:37:11
Original
1054 people have browsed it

How to Flatten a Multidimensional Array in PHP?

Flattening Multidimensional Arrays into One Dimension

Converting a multidimensional array with numeric keys into a one-dimensional array can be a daunting task. To simplify this process, we present a reliable solution.

To flatten the multidimensional array, we utilize array_reduce() with the array_merge callback function. array_reduce() accumulates an array by iteratively applying the callback function to each element in the original array, passing along an accumulator value.

In our case, we pass the array_merge callback, which combines two arrays into a single array. The initial accumulator value is set as an empty array.

array_reduce($array, 'array_merge', array())
Copy after login

Here's an example to illustrate this solution:

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

The resulting array, $result, will be:

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

This approach provides a concise and straightforward way to flatten multidimensional arrays with numeric keys into a one-dimensional structure.

The above is the detailed content of How to Flatten a Multidimensional 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