php 重置php中数组元素的键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10492839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reset keys of array elements in php?
提问by Leo Chan
The question is how to reset key e.g. for an array:
问题是如何重置例如数组的键:
Array (
[1_Name] => Array (
[1] => leo
[4] => NULL
)
[1_Phone] => Array (
[1] => 12345
[4] => 434324
)
)
reset to :
重置为:
Array (
[1_Name] => Array (
[0] => leo
[1] => NULL
)
[1_Phone] => Array (
[0] => 12345
[1] => 434324
)
)
回答by deceze
To reset the keys of all arrays in an array:
重置数组中所有数组的键:
$arr = array_map('array_values', $arr);
In case you just want to reset first-level array keys, use array_values()without array_map.
如果您只想重置第一级数组键,请使用array_values()不带array_map.
回答by deceze
$array[9] = 'Apple';
$array[12] = 'Orange';
$array[5] = 'Peach';
$array = array_values($array);
through this function you can reset your array
通过此功能,您可以重置阵列
$array[0] = 'Apple';
$array[1] = 'Orange';
$array[2] = 'Peach';
回答by Andreas Wong
Use array_valuesto reset keys
使用array_values复位键
foreach($input as &$val) {
$val = array_values($val);
}
回答by Mahdi
Here you can see the difference between the way that decezeoffered comparing to the simple array_valuesapproach:
在这里,您可以看到deceze提供的方式与简单array_values方法之间的区别:
The Array:
数组:
$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);
In decezeway, here is your output:
在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
)
)
)
And here is your output if you only use array_valuesfunction:
如果您只使用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
)
)
)
回答by Skit
$result = ['5' => 'cherry', '7' => 'apple'];
array_multisort($result, SORT_ASC);
print_r($result);
Array ( [0] => apple [1] => cherry )
数组( [0] => 苹果 [1] => 樱桃)
//...
array_multisort($result, SORT_DESC);
//...
Array ( [0] => cherry [1] => apple )
数组( [0] => 樱桃 [1] => 苹果)
回答by William Espindola
PHP native function exists for this. See http://php.net/manual/en/function.reset.php
PHP 本机函数为此而存在。见http://php.net/manual/en/function.reset.php
Simply do this: mixed reset ( array &$array )
只需这样做: mixed reset ( array &$array )

