Home >Backend Development >PHP Tutorial >How Can PHP's `array_column` Function Flatten a Multidimensional Array?

How Can PHP's `array_column` Function Flatten a Multidimensional Array?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 00:01:151015browse

How Can PHP's `array_column` Function Flatten a Multidimensional Array?

Convert Multidimensional Array into Single Array with PHP's array_column Function

Navigating multidimensional arrays can be a cumbersome task. Especially when working with arrays that have excessive dimensions for seemingly no reason. Here's a solution to flatten such arrays into a simplified single array using PHP's array_column() function.

The Problem Statement:

We're given a multidimensional array with an unnecessary depth:

$array = [
    [
        ['plan' => 'basic'],
        ['plan' => 'small'],
        ['plan' => 'novice'],
        ['plan' => 'professional'],
        ['plan' => 'master'],
        ['plan' => 'promo'],
        ['plan' => 'newplan']
    ]
];

The Goal:

Our objective is to convert this multidimensional array into a simpler single array with the following structure:

$newArray = ['basic', 'small', 'novice', 'professional', 'master', 'promo', 'newplan'];

The Solution:

The array_column() function comes to our rescue. It allows us to extract a column of values from a multidimensional array based on a specified key:

$newArray = array_column($array, 'plan');

Here, the first argument is the array we wish to flatten. The second argument specifies the key ('plan') from which we want to extract the values.

How array_column Works:

array_column() iterates over the multidimensional array and for each inner array, it retrieves the value corresponding to the specified key. It then creates a new array with these extracted values.

Additional Note:

The array_column() function is straightforward to use and can greatly simplify working with complex arrays. For more information and examples, refer to the official PHP documentation at:

https://www.php.net/manual/en/function.array-column.php

The above is the detailed content of How Can PHP's `array_column` Function Flatten a Multidimensional Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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