2014-02-20 75 views
0

我想不通爲什麼asort不工作。其他任何排序都不起作用。 $ hs ['hs_type']是來自MySQL查詢的值。如何按值保存鍵的數組進行排序?

$results = $query->result_array(); 
$hs_types = array(); 
foreach($results as $hs) { 
    $hs_types[$hs['hs_type']]++; 
} 

$projects = array(); 
foreach($hs_types as $hs) { 
    array_push($projects, $hs); 
} 
asort($projects); 

的var_dump我前陣排序:數組(大小= 15)

* 8 => int 1709 
    * 13 => int 26 
    * 7 => int 474 
    * 14 => int 800 
    * 11 => int 282 
    * 6 => int 61 
    * 5 => int 23 
    * 15 => int 181 
    * 3 => int 2 
    * 19 => int 3 
    * 9 => int 50 
    * 1 => int 44 
    * 2 => int 2 
    * 4 => int 4 
    * 18 => int 13 

的var_dump我陣列後排序:數組(大小= 15)

* 8 => int 2 
    * 12 => int 2 
    * 9 => int 3 
    * 13 => int 4 
    * 14 => int 13 
    * 6 => int 23 
    * 1 => int 26 
    * 11 => int 44 
    * 10 => int 50 
    * 5 => int 61 
    * 7 => int 181 
    * 4 => int 282 
    * 2 => int 474 
    * 3 => int 800 
    * 0 => int 1709 

我想要的:

* 3 => int 2 
    * 2 => int 2 
    * 19 => int 3 
    * 4 => int 4 
    * 18 => int 13 
    * 5 => int 23 
    * 13 => int 26 
    * 1 => int 44 
    * 9 => int 50 
    * 15 => int 181 
    * 11 => int 282 
    * 7 => int 474 
    * 14 => int 800 
    * 8 => int 1709 
+1

請顯示您的排序代碼。 – deceze

回答

1

問題是,你得到的一切爲您很好的鍵陣列,然後推每個項目在$項目陣列(丟失密鑰),然後在$ projects數組上進行分配。

它表明了這個小測試腳本: -

<?php 

$hs_types = array(8 => 1709, 
    13 => 26, 
    7 => 474, 
    14 => 800, 
    11 => 282, 
    6 => 61, 
    5 => 23, 
    15 => 181, 
    3 => 2, 
    19 => 3, 
    9 => 50, 
    1 => 44, 
    2 => 2, 
    4 => 4, 
    18 => 13); 

Echo "\r\nOriginal array\r\n"; 
print_r($hs_types); 

$projects = array(); 
foreach($hs_types as $hs) 
{ 
    array_push($projects, $hs); 
} 

asort($projects); 

Echo "\r\nPushed array sorted\r\n"; 
print_r($projects); 

asort($hs_types); 

Echo "\r\nOriginal array sorted\r\n"; 
print_r($hs_types); 

?> 

,但它看起來像它會更容易剛剛得到的排序列表中的SQL擺在首位。

0

我試着用你的arra y隨ASORT()和它的工作完美,回來跟您預期的結果:

<?php 
//your array 
$a = array(
    8 => 1709, 
    13 => 26, 
    7 => 474, 
    14 => 800, 
    11 => 282, 
    6 => 61, 
    5 => 23, 
    15 => 181, 
    3 => 2, 
    19 => 3, 
    9 => 50, 
    1 => 44, 
    2 => 2, 
    4 => 4, 
    18 => 13 
); 

//print unsorted array 
print_r($a); 

//sort the array 
asort($a); 

//print the sorted array 
echo "<br/><br/>"; 
print_r($a); 

如果這真的不是爲你工作,爲什麼不這樣做在SQL查詢,而不是排序?那麼你不需要費心去重新排序在PHP中。

0

您確定您使用的是asort而不是sort?我想你的代碼,它完美的作品:

<?php 

$myArray = array(
    8 => 1709, 
    13 => 26, 
    7 => 474, 
    14 => 800, 
    11 => 282, 
    6 => 61, 
    5 => 23, 
    15 => 181, 
    3 => 2, 
    19 => 3, 
    9 => 50, 
    1 => 44, 
    2 => 2, 
    4 => 4, 
    18 => 13, 
); 

var_dump($myArray); 

asort($myArray); 
var_dump($myArray); 
?> 

我的結果:

enter image description here