2012-12-01 107 views
0

問題:如何用對象對多維數組進行排序?我有一個如下的數組。如何用對象對多維數組進行排序?

array(3) { 
    [0]=> 
    object(Photo_model)#25 (5) { 
    ["id"]=> 
    int(5) 
    ["file_name"]=> 
    string(36) "A49361605AE049D687CDC3FEAF7D3236.jpg" 
    ["user_id"]=> 
    int(1) 
    ["challenge_id"]=> 
    string(1) "2" 
    ["score"]=> 
    int(19) 
    } 
    [1]=> 
    object(Photo_model)#28 (5) { 
    ["id"]=> 
    int(2) 
    ["file_name"]=> 
    string(36) "A49361605AE049D687CDC3FEAF7D3236.jpg" 
    ["user_id"]=> 
    int(1) 
    ["challenge_id"]=> 
    string(1) "2" 
    ["score"]=> 
    int(10) 
    } 
    [2]=> 
    object(Photo_model)#29 (5) { 
     ["id"]=> 
     int(3) 
     ["file_name"]=> 
     string(36) "A49361605AE049D687CDC3FEAF7D3236.jpg" 
     ["user_id"]=> 
     int(1) 
     ["challenge_id"]=> 
     string(1) "2" 
     ["score"]=> 
     int(15) 
    } 
} 

我試圖按分數排序上面的數組。我創建瞭如下功能。

aarsort (&$array, 'score'); 
function aarsort (&$array, $key) { 
    $sorter=array(); 
    $ret=array(); 
    reset($array); 
    foreach ($array as $ii => $va) { 
     $sorter[$ii]=$va[$key]; 
    } 
    arsort($sorter); 
    foreach ($sorter as $ii => $va) { 
     $ret[$ii]=$array[$ii]; 
    } 
    $array=$ret; 
} 

但它不工作。我怎樣才能按鍵排序多維數組(score)?

結果應該是由ID => 5,3,2

回答

3

你的陣列僅僅是1維的,並且在每個陣列項的對象。

畢竟,排序一維數組組成的對象,而排序的對象的某些屬性,請使用usort

usort($array, function($a, $b) { 
    return $a->score - $b->score 
}); 

要想從以上,只是循環id => 5, 3, 2通過從數組上面的代碼和訪問屬性來獲得它

$ids = array(); 
foreach ($array as $item) { 
    $ids[] = $item->id; 
} 
var_dump($ids); 

而且我不知道如果順序是正確的。如果結果是倒序,只是否定usort函數中的閉包結果。

+0

我想排序得分列arrary做這個問題。我怎麼能夠? –

+0

'score'是你的對象的一個​​屬性,根據你的數組的'var_dump' ... – luiges90

0

它只是一個例子。

//$newarray for store all array id 
//$array is your previous array . You just enter your all index whose key id store in new array 
$newarray = array(); 
foreach($array as $obj => $id) 
{ 
    $newarray[] = $id[$key]; 
} 

array_multisort($newarray,SORT_ASC,$array); 
0

我已經php.net

// Obtain a list of columns 
       foreach ($array as $key => $row) { 
        $_score[$key] = $row->score; 
       } 

       // Sort the data with volume descending, edition ascending 
       // Add $data as the last parameter, to sort by the common key 
       array_multisort($_score, SORT_DESC, $array); 
相關問題