可能这很容易通过本机php函数实现,但我似乎无法在手册中找到它。 我有类似下面的数组:
[0] (Array)#3
[date_published] "2011-10-10 21:25:56"
[domain] "gawker.com"
[domain_rank] "909"
[language] "en"
[publisher] ""MAIN" via Steve in Google Reader"
[title] "Genetically-modified salmon are closer than ever to a dinner plate near you [Genetic Engineering]"
[url] "http://feeds.gawker.com/~r/io9/full/~3/s_6bCNerlW0/genetically+modified-salmon-are-closer-than-ever-to-a-dinner-plate-near-you"
[1] (Array)#4
[date_published] "2011-10-10 21:06:00"
[domain] "huffingtonpost.com"
[domain_rank] "85"
[publisher] "PoliticsPolitics | Politics"
[title] "John Geyman: Health Care: A Casualty of Class Warfare"
[url] "http://feeds.huffingtonpost.com/~r/HP/Politics/~3/ZsqVSZMcWKM/health-care-statistics-america_b_990263.html"
我希望通过domain_rank订购它,我怎样才能通过PHP实现这个目标?
答案 0 :(得分:4)
<?php
$array = array(
array('domain_rank' => 909, 'a'),
array('domain_rank' => 100, 'b'),
array('domain_rank' => 500, 'c'),
array('domain_rank' => 100, 'd')
);
// since php 5.3
usort($array, function ($a, $b) {
return $a['domain_rank'] > $b['domain_rank'];
});
// below php 5.3
function sortByDomainRank($a, $b) {
return $a['domain_rank'] > $b['domain_rank'];
}
usort($array, 'sortByDomainRank');
print_r($array);
?>
比照http://php.net/manual/en/function.usort.php允许您为排序提供回调函数。
答案 1 :(得分:0)
这是一种方式,而不是最好的方式。
function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
$data = subval_sort($data,'domain_rank');
你也可以像这样使用Usort:
function compare($a, $b) {
return ($a['domain_rank'] < $b['domain_rank']);
}
usort($data, 'compare');
答案 2 :(得分:-2)
根据您的具体需要,有几个PHP函数可以处理这个问题。看看php手册,因为它是你的朋友。最好的朋友甚至。