如何重新索引一个多维数组的所有子数组元素?

问题是如何重置键,例如:

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

重置为:

Array (
[1_Name] => Array (
[0] => leo
[1] => NULL
)
[1_Phone] => Array (
[0] => 12345
[1] => 434324
)
)
262936 次浏览

使用 array_values重置键

foreach($input as &$val) {
$val = array_values($val);
}

Http://php.net/array_values

重置数组中所有数组的键:

$arr = array_map('array_values', $arr);

如果您只是想重置一级数组键,请使用不带 array_maparray_values()

$array[9] = 'Apple';
$array[12] = 'Orange';
$array[5] = 'Peach';


$array = array_values($array);

通过这个函数你可以重置你的数组

$array[0] = 'Apple';
$array[1] = 'Orange';
$array[2] = 'Peach';

在这里,你可以看到与简单的 array_values方法相比,谢谢提供的方法有所不同:

数组:

$array['a'][0] = array('x' => 1, 'y' => 2, 'z' => 3);
$array['a'][5] = array('x' => 4, 'y' => 5, 'z' => 6);


$array['b'][1] = array('x' => 7, 'y' => 8, 'z' => 9);
$array['b'][7] = array('x' => 10, 'y' => 11, 'z' => 12);

deceze的方式,下面是您的输出:

$array = array_map('array_values', $array);
print_r($array);


/* Output */


Array
(
[a] => Array
(
[0] => Array
(
[x] => 1
[y] => 2
[z] => 3
)
[1] => Array
(
[x] => 4
[y] => 5
[z] => 6
)
)
[b] => Array
(
[0] => Array
(
[x] => 7
[y] => 8
[z] => 9
)


[1] => Array
(
[x] => 10
[y] => 11
[z] => 12
)
)
)

如果你只使用 array_values函数,这里是你的输出:

$array = array_values($array);
print_r($array);


/* Output */


Array
(
[0] => Array
(
[0] => Array
(
[x] => 1
[y] => 2
[z] => 3
)
[5] => Array
(
[x] => 4
[y] => 5
[z] => 6
)
)
[1] => Array
(
[1] => Array
(
[x] => 7
[y] => 8
[z] => 9
)
[7] => Array
(
[x] => 10
[y] => 11
[z] => 12
)
)
)

PHP 本机函数为此存在。参见 http://php.net/manual/en/function.reset.php

只需要这样做: mixed reset ( array &$array )

$result = ['5' => 'cherry', '7' => 'apple'];
array_multisort($result, SORT_ASC);
print_r($result);

数组([0] = > apple [1] = > cherry)

//...
array_multisort($result, SORT_DESC);
//...

数组([0] = > 樱桃[1] = > 苹果)