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

How Can I Flatten a Multidimensional Array into a Single-Dimension Array in PHP?

Linda Hamilton
Release: 2024-12-20 20:17:10
Original
152 people have browsed it

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']
    ]
];
Copy after login

You wish to convert this array into the following simplified form:

$simplifiedArray = [
    'basic',
    'small',
    'novice',
    'professional',
    'master',
    'promo',
    'newplan'
];
Copy after login

To achieve this conversion, PHP offers a powerful function called array_column:

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

Here's how array_column works:

  • First argument: The multidimensional array you want to convert.
  • Second argument: The key of the subarray that contains the element you want to extract. In this case, it's 'plan'.

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!

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