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
Linda HamiltonOriginal
2024-12-20 20:17:10153browse

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:

  • 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!

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