如何根据特定值按降序对数组进行排序[重复]
Posted
技术标签:
【中文标题】如何根据特定值按降序对数组进行排序[重复]【英文标题】: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' 但无法正确找到结果,谁能建议我?
【问题讨论】:
uksort: 试试第一个例子…… 发布您的 usort() 尝试,usort 应该可以工作,因为它将使用元素的 VALUE 而不是键 ***.com/questions/2699086/… php.net/manual/en/array.sorting.php 【参考方案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');
你可以使用类中的函数或静态方法 - 你的选择:)
【讨论】:
以上是关于如何根据特定值按降序对数组进行排序[重复]的主要内容,如果未能解决你的问题,请参考以下文章