2013-10-11 38 views
-1

我有一個數組,其中包含60個元素,需要對它進行排序(從低到高)並且必須獲得前10個該排序數組的元素作爲另一個數組。我被卡住了。任何幫助將是偉大的!根據數值對數組進行排序,並獲得前n個元素作爲排序數組的其他數組

到目前爲止,我有 -

$lists_store = get_stores($user_location); 
    asort($lists_store); // this give me sorted array as expected 

echo "<pre>"; 
print_r($lists_store); 
exit; 

將輸出..

Array 
(
    [39] => 6291 
    [52] => 6293 
    [63] => 6322 
    [64] => 6323 
    [46] => 6327 
    [37] => 6338 
    [26] => 6341 
    [44] => 6346 
    [20] => 6346 
    [17] => 6346 
    [11] => 6349 
    [43] => 6349 
    [24] => 6350 
    [21] => 6351 
    [12] => 6351 
    [10] => 6352 
    [27] => 6354 
    [22] => 6354 
    [19] => 6355 ..... 

現在問題就來了這裏..

$lists_store = array_slice($lists_store, 0, 10); // gives me first 10 elements of array but on the key basis 

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 
(
    [39] => 6291 
    [52] => 6293 
    [63] => 6322 
    [64] => 6323 
    [46] => 6327 
    [37] => 6338 
    [26] => 6341 
    [44] => 6346 
    [20] => 6346 
    [17] => 6346 
) 
+0

'list_store = array_chunk($ lists_store,10,true);' – bansi

+0

你讀過['array_chunk'](http://php.net/array_chunk)的*文檔*嗎? – deceze

+0

我更新了我的問題,我正在使用array_slice,並且我在這裏提到的結果也是array_slice – codepixlabs

回答

2

,如果你想獲得陣列的一部分,我認爲你應該使用array_slice

請注意,默認情況下,array_slice()將重新排序並重置數字數組 索引。您可以通過將 preserve_keys設置爲TRUE來更改此行爲。

嘗試使用

$lists_store = array_slice($lists_store, 0, 10, true); 

參考:http://www.php.net/manual/en/function.array-slice.php

+0

對不起,我更新了我的問題,我只使用array_slice,它正在重置密鑰 – codepixlabs

+0

您應該將第四個參數設置爲true以保留鍵。 – bansi

+0

謝謝..幫忙 – codepixlabs

2

array_chunk()的文件表明,有一個第三個可選的布爾參數保持鍵,所以如果你這樣做:

$lists_store = array_chunk($lists_store, 10, true); 

如你預期它可能工作

但你應該真的使用array_slice()作爲array_chunk()將數組分割成片段array_slice() j烏斯採取指定部分,它適合更適合你正在尋找

$lists_store = array_slice($lists_store, 0, 10, true); // the last parameter is used to preserve the keys 
+0

謝謝你的伎倆.. – codepixlabs

1

使用array_slice什麼(數組$陣列,詮釋$抵銷[摘要$長度= NULL [,布爾$ preserve_keys =假])

最後一個參數如果設置爲「true」,那麼您的密鑰將被保留。

+0

謝謝你的幫助我錯過了 – codepixlabs

相關問題