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

How to Reindex Subarrays in a Multidimensional Array?

DDD
Release: 2024-11-05 15:37:02
Original
205 people have browsed it

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

We aim to transform it into:

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

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>
Copy after login

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>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template