How to Re-index Subarray Elements in a Multidimensional Array in PHP?

Mary-Kate Olsen
Release: 2024-11-05 00:58:01
Original
650 people have browsed it

How to Re-index Subarray Elements in a Multidimensional Array in PHP?

Re-indexing Multidimensional Array Subarray Elements

In PHP, arrays are often used to store complex data structures, including multidimensional arrays. Sometimes, it becomes necessary to reset the keys of the subarrays within a multidimensional array.

For example, consider the following multidimensional array with non-sequential keys:

Array (
    [1_Name] => Array (
        [1] => leo
        [4] => NULL
    )
    [1_Phone] => Array (
        [1] => 12345
        [4] => 434324
    )
)
Copy after login

The goal is to reset the keys of the subarrays to start from zero:

Array (
    [1_Name] => Array (
        [0] => leo
        [1] => NULL
    )
    [1_Phone] => Array (
        [0] => 12345
        [1] => 434324
    )
)
Copy after login

Solution

To reset the keys of all subarrays in the multidimensional array, you can use the array_map() function together with the array_values() function:

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

The array_values() function returns a new array with sequential numeric keys from the input array, effectively resetting the keys. The array_map() function applies the array_values() function to each subarray in the original array, resulting in a new multidimensional array with re-indexed subarrays.

Note:

If you only want to reset the keys of the first-level subarrays without applying the re-indexing to nested subarrays, you can use array_values() directly without using array_map():

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

The above is the detailed content of How to Re-index Subarray Elements in a Multidimensional 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