2011-03-31 45 views
2

關聯數組我有mysql表即如何排序在PHP

 
id | a | b | c | d |ud_id 
1 | 20| 8 | 45| 18| 1 

現在我想找回在PHP排序數組的數據和在這個例子中找到的最高場(C = 45)

 
$query="SELECT `a`, `b`, `c`, `d` from table where ud_id=1"; 
$rs=mysql_query($query) or die(mysql_error()); 
$row=mysql_fetch_array($rs); 


但我怎麼可以排序此關聯數組,並找到最關鍵的。

+1

看來你的數據庫設計是錯誤的。你必須找到最高的使用SQL,而不是PHP – 2011-03-31 09:46:15

+0

與Col. Shrapnel同意,表格設計不適合這個。 – 2011-03-31 10:07:18

回答

5

PHP有一大堆排序功能。

的一個聽起來像你想要的是asort()

查看PHP手冊的其他替代品,如sort()ksort()natsort()usort(),和一些其他的變化。還有shuffle()隨機排序。

[編輯] 好了,一步一步得到的最高值了數組:

asort($row); //or arsort() for reverse order, if you prefer. 
end($row); //positions the array pointer to the last element. 
print current($row); //prints "45" because it's the sorted highest value. 
print key($row); //prints "c" because it's the key of the hightst sorted value. 

還有一大堆其他的方法來做到這一點爲好。

+0

當我使用'print_r(sort($ row));'這給了我結果1,我想高鍵值像'['c'] => 45' – 2011-03-31 09:31:07

+0

@source:好吧,那麼如果你嘗試asort()'如我所說? – Spudley 2011-03-31 09:33:19

+0

好吧我使用'asort($ row); print_r($ row)',結果是Array [[1] => 8 [b] => 8 [3] => 18 [d] => 18 [0] => 20 [a] => 2] => 45 [c] => 45)'那麼我怎樣才能從這個數組中獲得最高值。 – 2011-03-31 09:40:50

2

就像@Spudley說的那樣,arsort就是答案。您可以通過獲取第一個array_keys來得到結果數組的第一個鍵。

// ... 
$row = mysql_fetch_assoc ($rs); 
arsort ($row); 
$keys = array_keys ($row); 
printf ("key: %s, value: %s", $keys[0], $row[$keys[0]]); 

另請注意mysql_fetch_assoc

+0

但'asort'按升序對數組進行排序,並希望按降序對數組進行排序,以便在第一個偏移處應該有最高值。 – 2011-03-31 09:47:16

+0

然後''arsort' ... – vbence 2011-03-31 09:49:07

+0

@source - 如果您閱讀我鏈接到的手冊**頁面,您會看到'asort()'有一個匹配的函數'arsort()'來執行相反的順序排序。 – Spudley 2011-03-31 09:49:11