Home > Backend Development > PHP Tutorial > How to Re-index Subarray Elements in Multidimensional Arrays?

How to Re-index Subarray Elements in Multidimensional Arrays?

Mary-Kate Olsen
Release: 2024-11-05 14:50:03
Original
724 people have browsed it

How to Re-index Subarray Elements in Multidimensional Arrays?

Re-indexing Subarray Elements in Multidimensional Arrays

In multidimensional arrays, resetting key indices can be useful for maintaining a predictable order or aligning values with other arrays.

Problem:

How do you reset the keys of subarrays within a multidimensional array, renumbering them sequentially from zero? Consider the following example:

<code class="php">$arr = [
    '1_Name' => [
        1 => 'leo',
        4 => null
    ],
    '1_Phone' => [
        1 => 12345,
        4 => 434324
    ]
];
// Expected output:
// Array (
//     [1_Name] => [
//         0 => 'leo',
//         1 => null
//     ]
//     [1_Phone] => [
//         0 => 12345,
//         1 => 434324
//     ]
// )</code>
Copy after login

Solution:

To achieve this, you can use the following approach:

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

The array_map() function applies the array_values() function to each subarray within $arr. array_values() re-indexes the subarray's keys sequentially from zero.

<code class="php">// array_values() for first-level arrays only
$arr = array_values($arr);</code>
Copy after login

For first-level array key resetting, you can use array_values() without array_map().

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