2013-04-23 103 views
0

我試圖根據SQL數據庫中未排序的數組創建一個有序數組。排序數組 - 從外部數據對數組排序

是從數據庫中得到看起來像這樣的數據:

Array (
    //array ('name', position) 
    array ('george', 2), 
    array ('lenny' , 4), 
    array ('rabbit', 1), 
    array ('pet' , 3) 
) 

的想法是在數組中的名字',其中position有放置在數組中排序。 我想做些什麼來最終被:

Array ('rabbit', 'george', 'pet', 'lenny') 

目前的辦法,我已經嘗試這是使用split_array()

$result是從數據庫中排列。

foreach ($result as $res){ 
    $a = array(array($res['name'], $res['position'])); 
    array_splice($finalArray, ($res['position'] - 1), 0, $a); 
} 

問題有時根據用戶檢索就不能正確排序它的順序,有沒有更好的方式來做到這一點,還是這個好,我做錯了? 謝謝。

+3

爲什麼不作爲查詢的一部分在數據庫中排序? 'SELECT name,ord FROM table ORDER BY ord' – 2013-04-23 08:02:34

+0

@AleksG我現在感覺很糟糕:(大聲笑很簡單,謝謝! – MichaelMitchell 2013-04-23 08:10:03

+0

只是微笑和使用它 – 2013-04-23 08:16:51

回答

2

使用uasorthttp://php.net/manual/en/function.uasort.php功能,您可以通過用戶定義的比較討論function這樣的:

$myArray = array(array('bill',3),array('joe',4),array('john',1)); 

/** 
* @desc compare two arrays by the second element 
* @param array $a (array to compare with an other) 
* @param array $b (array to compare with an other) 
* @return int 0|1|-1 equals|first is bigger|second is bigger 
*/ 
function myCompare($a,$b){ 
    if($a[1] == $b[1]){ 
     return 0;  //if the 2nd elements equals return 0 
    } 
    return ($a[1] > $b[1])?1:-1; //if the 2nd element of the 1st parameters is bigger returns 1 , else returns -1 
} 

用法:

uasort($myArray, 'myCompare'); 

uasort manipolates代替原來array

結果:

var_dump($myArray); 

array(
     array('john',1), 
     array('bill',3), 
     array('joe',4) 
); 

建議:

如果你能與ORDER BY指令這樣的編輯SQL查詢,更好地做空結果查詢:

SELECT `name`,`position` 
FROM `mytable` #your table name 
WHERE 1 #or your conditions here 
ORDER BY `position` ASC #ordering directive 

這應該跑得更快。如果使用這個,建議將index添加到position字段。