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

How to Re-index Subarray Elements in Multidimensional Arrays?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-05 14:50:03645browse

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>

Solution:

To achieve this, you can use the following approach:

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

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>

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!

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