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

How Can I Efficiently Flatten a Multidimensional Array in PHP?

Mary-Kate Olsen
Release: 2024-12-21 14:31:13
Original
536 people have browsed it

How Can I Efficiently Flatten a Multidimensional Array in PHP?

Converting Multidimensional Array to Single Array

You have a multidimensional array that appears unnecessarily complex and you desire to flatten it into a single array. An efficient solution to this problem exists.

The array_column function, which is built into PHP, can help you achieve this task. It takes two arguments: the input array and the key name (or array of keys) to extract. In your case, you want to extract the plan key and create a new array based solely on it.

The code to implement this is straightforward:

$array = array_column($array, 'plan');
Copy after login

The result will be a single array, as desired:

print_r($array);

// Output:
// Array
// (
//     [0] => basic
//     [1] => small
//     [2] => novice
//     [3] => professional
//     [4] => master
//     [5] => promo
//     [6] => newplan
// )
Copy after login

For more information on the array_column function and its usage, refer to the official PHP documentation: https://www.php.net/manual/en/function.array-column.php.

The above is the detailed content of How Can I Efficiently 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