【问题标题】:How to sort array in descending order based on a specific value [duplicate]如何根据特定值按降序对数组进行排序[重复]
【发布时间】:2013-03-06 17:54:01
【问题描述】:

我有很多新闻,比如

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' 但无法正确找到结果,谁能建议我?

【问题讨论】:

标签: php arrays


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:
    <?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);
    
     ?>
    

    【讨论】:

      【解决方案3】:

      或者这个:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-26
        • 2021-09-06
        • 2021-10-12
        • 2020-03-06
        • 2012-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多