如何根据特定值按降序对数组进行排序

时间:2013-03-18 11:48:19

标签: php arrays

我有一系列新闻,比如

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'但是无法找到正确的结果可以有人建议我吗?

3 个答案:

答案 0 :(得分:8)

试试这个:

$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);

答案 1 :(得分: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);

 ?>

答案 2 :(得分: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');

你可以使用类中的函数或静态方法 - 你的选择:)