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 ) )
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 ) )
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>
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>
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!