我有一个相当大的数组,看起来像
Array(
[0] => stdClass Object
(
[id] => 8585320
[title] => the title
[type] => page
[url] => link.com
[excerpt] => brief description
)
[1] => stdClass Object
(
[id] => 8585320
[title] => the title
[type] => page
[url] => link.com
[excerpt] => brief description
)
)
我对数组的形成方式以及它是如何产生的没有明显的控制,似乎几乎没有任何逻辑。但我被困住了。所以我需要做的基本上是按每个 stdClass 对象对数组进行数字排序,然后确保 id 从大到小,而不是从小到大。始终保持数组对象组合的当前结构
我现在甚至无法开始思考我需要如何以我需要的方式对其进行排序。因为它已经足够长的一天了。
更新
public function updateRet($a, $b) {
return $b->id - $a->id;
}
usort($ret, 'updateRet');
只需使用 usort
:
function compare_some_objects($a, $b) { // Make sure to give this a more meaningful name!
return $b->id - $a->id;
}
// ...
usort($array, 'compare_some_objects');
如果您有 PHP 5.3 或更高版本,您还可以使用匿名函数:
usort($array, function($a, $b) { return $b->id - $a->id; });