Home >Backend Development >PHP Tutorial >How to Reindex Subarrays in a Multidimensional Array?

How to Reindex Subarrays in a Multidimensional Array?

DDD
DDDOriginal
2024-11-05 15:37:02209browse

How to Reindex Subarrays in a Multidimensional Array?

Reindexing Subarrays of Multidimensional Arrays

Question:

How do we reset the keys of all subarrays within a multidimensional array? For instance, consider the array:

[
    '1_Name' => [
        '1' => 'leo',
        '4' => null
    ],
    '1_Phone' => [
        '1' => '12345',
        '4' => '434324'
    ],
]

We aim to transform it into:

[
    '1_Name' => [
        '0' => 'leo',
        '1' => null
    ],
    '1_Phone' => [
        '0' => '12345',
        '1' => '434324'
    ],
]

Answer:

To re-index the keys of all arrays within an array, we employ array_map in conjunction with array_values. Here's the code:

<code class="php">$arr = array_map('array_values', $arr);</code>

array_values resets the keys of a single array, while array_map applies this operation to every subarray in the parent array.

Alternatively, if we only need to re-index the keys of the first-level arrays, we can use array_values directly:

<code class="php">$arr = array_values($arr);</code>

The above is the detailed content of How to Reindex Subarrays in 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