2013-12-15 374 views
0

我有以下結構的陣列:PHP排序特定字段陣列

Array ([0] => Array ([event] => event1 [Weight] => 2) 

,我試圖通過「權重」進行排序。我試過這個:

function cmp($a, $b) { 
    if ($a['Weight'] > $b['Weight']){ 
     return -1; 
    } else { 
     return 1; 
    } 
} 

但它不是按重量分類。這似乎是我如何稱重,但我不確定如何正確地做到這一點。

+2

實際啓動排序的行在哪裏?必須有'usort()'之類的東西。這是一個正確的例子:https://eval.in/79635 – ComFreek

回答

1

您可以這樣排序是:

uasort($array, function ($a, $b) { 
    $c = $a['Weight']; 
    $d = $b['Weight']; 
    if ($c == $d){ 
     return 0; 
    } 
    else if($c > $d){ 
     return 1; 
    } 
    else{ 
     return -1; 
    } 
}); 
0
<?php 
// Obtain a list of columns 
//$data = Your Array 
foreach ($data as $key => $row) { 
    $weight[$key] = $row['Weight']; 
} 

// Sort the data with volume descending, edition ascending 
// Add $data as the last parameter, to sort by the common key 
array_multisort($weight, SORT_ASC, $data); 
?> 
0

我覺得你的問題一定是你所使用的實際的排序功能,下面是如何在乙醚升序或一個完整的例子降序。

$array = array(
     array('event'=> 'something', 'Weight' => 2), 
     array('event'=> 'something', 'Weight' => 1), 
     array('event'=> 'something', 'Weight' => 10), 
     array('event'=> 'something', 'Weight' => 10), 
     array('event'=> 'something', 'Weight' => 0), 
     array('event'=> 'something', 'Weight' => 1), 
     array('event'=> 'something', 'Weight' => -10), 
    ); 

function weightCmp($isAscending = true) { 
    return function($a, $b) use ($isAscending) { 
     $diff = $a['Weight'] - $b['Weight']; 
     return $isAscending ? $diff : $diff * -1; 
    }; 
} 

usort($array, weightCmp()); 
var_dump($array); 

usort($array, weightCmp(false)); 
var_dump($array);