2013-03-18 80 views
0

我的新聞像如何排序基於特定值

Array 
(
    [0] => Array 
    (
     [news_published] => 1337192831 
     [news_category] => 5 
    ) 

    [1] => Array 
    (
     [news_published] => 1334566743 
     [news_category] => 5 
    ) 

    [2] => Array 
    (
     [news_published] => 1340092425 
     [news_category] => 6 
    ) 

    [3] => Array 
    (
     [news_published] => 1339740173 
     [news_category] => 6 
    ) 

    [4] => Array 
    (
     [news_published] => 1336148837 
     [news_category] => 6 
    ) 
) 

如何我可以降序排序news_published數組按降序排列....我試圖與「usort」,但不能找到正確的結果任何人都可以建議我嗎?

+0

[uksort(HTTP: //www.php.net/manual/en/function.uksort.php):嘗試第一個例子... – 2013-03-18 11:50:14

+0

發佈你的usort()嘗試,usort應該工作,因爲它會使用元素的價值不是關鍵 – Waygood 2013-03-18 11:53:14

+1

http://stackoverflow.com/questions/2699086/sort-multidimensional-array-by-value-2 – 2013-03-18 11:53:36

回答

6

試試這個:

$arr = your array; 
$sort = array(); 
foreach($arr as $k=>$v) { 
    $sort['news_published'][$k] = $v['news_published']; 
} 

array_multisort($sort['news_published'], SORT_DESC, $arr); 

echo "<pre>"; 
print_r($arr); 
+0

Thanku它爲我工作... – Gautam3164 2013-03-18 12:59:38

0
<?php 


$array = array(array('news_published'=>'1337192831','news_category'=>'5'), 
      array('news_published'=>'1337192231','news_category'=>'5'),     
      array('news_published'=>'1337192921','news_category'=>'6'), 

      ); 
/orignal array 
print_r($array); 

foreach ($array as $key => $row) { 
$new_published[$key] = $row['news_published']; 
} 
array_multisort($new_published, SORT_DESC,$array); 

// sorted array 
print_r($array); 

?> 
0

或者這樣:

function sortForMe($a, $b) 
{ 
    if ((int)$a['news_published'] === (int)$b['news_published']) { 
     return 0; 
    } 
    return (int)$a['news_published'] < (int)$b['news_published'] ? -1 : 1; 
} 

usort($array, 'sortForMe'); 

您可以使用從類函數或靜態方法 - 你的選擇:)