Php 根据值对数组进行排序,并获取前n个元素作为排序数组的另一个数组
我有一个包含60个元素的数组,需要对其进行排序(从低到高),并将排序后的数组的前10个元素作为另一个数组。我被卡住了。任何帮助都会很好 到目前为止,我已经-Php 根据值对数组进行排序,并获取前n个元素作为排序数组的另一个数组,php,arrays,sorting,Php,Arrays,Sorting,我有一个包含60个元素的数组,需要对其进行排序(从低到高),并将排序后的数组的前10个元素作为另一个数组。我被卡住了。任何帮助都会很好 到目前为止,我已经- $lists_store = get_stores($user_location); asort($lists_store); // this give me sorted array as expected echo "<pre>"; print_r($lists_store); exit; 现在问题来了 Ar
$lists_store = get_stores($user_location);
asort($lists_store); // this give me sorted array as expected
echo "<pre>";
print_r($lists_store);
exit;
现在问题来了
Array
(
[0] => 6291
[1] => 6293
[2] => 6322
[3] => 6323
[4] => 6327
[5] => 6338
[6] => 6341
[7] => 6346
[8] => 6346
[9] => 6346
)
期望输出--
如果你想得到数组的一部分,我认为你应该使用
array\u slice
请注意,array_slice()将对数值数组进行重新排序和重置
默认情况下为索引。您可以通过设置
将_键保留为TRUE
试用
$lists_store = array_slice($lists_store, 0, 10, true); // the last parameter is used to preserve the keys
参考:与第三个参数“
preserve\u keys
”一起使用,而不是array\u chunk()
请参见此处的提琴:上的文档表明有第三个可选的布尔参数来保留键,因此如果您这样做:
它可能会像你预期的那样工作
但是您应该真正使用asarray\u chunk()
将数组分割成片段,array\u slice()
只取指定的部分,这更适合您所寻找的内容
使用数组_切片(数组$array,int$offset[,int$length=NULL[,bool$preserve_keys=false])
最后一个参数如果设置为“true”,则您的密钥将被保留。lists\u store=array\u chunk($lists\u store,10,true)代码>你有没有阅读文档?!我更新了我的问题,我使用的是array_slice,我在这里提到的结果也是array_slice。很抱歉,我更新了我的问题,我只使用array_slice重置密钥。您应该将第四个参数设置为true以保留密钥。
Array
(
[0] => 6291
[1] => 6293
[2] => 6322
[3] => 6323
[4] => 6327
[5] => 6338
[6] => 6341
[7] => 6346
[8] => 6346
[9] => 6346
)
Array
(
[39] => 6291
[52] => 6293
[63] => 6322
[64] => 6323
[46] => 6327
[37] => 6338
[26] => 6341
[44] => 6346
[20] => 6346
[17] => 6346
)
$lists_store = array_slice($lists_store, 0, 10, true);
$lists_store = array_chunk($lists_store, 10, true);
$lists_store = array_slice($lists_store, 0, 10, true); // the last parameter is used to preserve the keys