Home >Backend Development >PHP Tutorial >How Can I Flatten a Multidimensional Array into a Single-Dimension Array in PHP?
Converting Multidimensional Arrays into Single-Dimension Arrays
Multidimensional arrays can sometimes become unwieldy, especially when you need to work with the elements in a more straightforward way. Fortunately, PHP provides a concise method to convert multidimensional arrays into single-dimension arrays.
Consider the following multidimensional array:
$array = [ [ ['plan' => 'basic'], ['plan' => 'small'], ['plan' => 'novice'], ['plan' => 'professional'], ['plan' => 'master'], ['plan' => 'promo'], ['plan' => 'newplan'] ] ];
You wish to convert this array into the following simplified form:
$simplifiedArray = [ 'basic', 'small', 'novice', 'professional', 'master', 'promo', 'newplan' ];
To achieve this conversion, PHP offers a powerful function called array_column:
$simplifiedArray = array_column($array, 'plan');
Here's how array_column works:
By providing these parameters, array_column extracts the specified elements from the subarrays and creates a new single-dimension array with those elements. This simplifies your array structure and makes it easier to work with.
The above is the detailed content of How Can I Flatten a Multidimensional Array into a Single-Dimension Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!