我有這樣的事情:PHP按照一定的標準排序對象數組?
$i = 0;
foreach($tracks['results'] as $track){
$trackName[$i] = $track['name'];
$trackPlaycount[$track['name']] = $track['playcount'];
$trackPercent[$track['name']] = $track['percent'];
$i++;
}
$this->trackName = $trackName;
$this->trackPlaycount = $trackPlaycount;
$this->trackPercent = $trackPercent;
我怎麼可能通過playcount這些對象進行排序?從我目前閱讀的內容來看,我明白我應該創建一個比較函數,然後使它與usort()一起工作,對吧?但我不太清楚如何實現這一目標?
謝謝
編輯:好了,現在我有這樣的:
public function firstmethod(){
// there are some more parameters here of course
// but they worked before, not important for the problem
$i = 0;
foreach($tracks['results'] as $track){
$trackName[$i] = $track['name'];
$trackPlaycount[$track['name']] = $track['playcount'];
$trackPercent[$track['name']] = $track['percent'];
// this part is new
$tracksArray[$i] = array(
'name' => $trackName[$i],
'playcount' => $trackPlaycount[$track['name']],
'percentage' => $trackPercent[$track['name']]
);
$i++;
}
usort($tracksArray, array($this, 'sortByCount'));
$i = 0;
// this is to put the new sorted array into the old variables?
foreach($tracksArray as $temp){
$trackName[$i] = $temp['name'];
$trackPlaycount[$trackName[$i]] = $temp['playcount'];
$trackPercent[$trackName[$i]] = $temp['percentage'];
$i++;
}
$this->trackName = $trackName;
$this->trackPlaycount = $trackPlaycount;
$this->trackPercent = $trackPercent;
}
public function sortByCount($a, $b){
if($a["playcount"] == $b["playcount"]) {
return 0;
}
return ($a["playcount"] < $b["playcount"]) ? -1 : 1;
}
This now works ... 謝謝大家
編輯我的答案,所以它包括整數字段排序,如果這給你的麻煩,希望它可以幫助 – edorian 2010-08-18 12:27:58