chr*_*ris 5 php arrays sorting
我有一个相当大的数组,看起来像
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
)
)
Run Code Online (Sandbox Code Playgroud)
我对阵列的形成方式没有明显的控制,以及它是如何出现的,似乎它几乎没有任何逻辑.但我坚持下去.所以我需要做的是基本上对每个stdClass对象进行数值排序,然后确保id从最大到最小,而不是从最小到最大.一直保持数组对象组合的当前结构
我现在甚至无法开始思考如何按照我需要的方式对其进行排序.因为它已经足够长的一天了.
UPDATE
public function updateRet($a, $b) {
return $b->id - $a->id;
}
usort($ret, 'updateRet');
Run Code Online (Sandbox Code Playgroud)
Ry-*_*Ry- 10
只需使用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');
Run Code Online (Sandbox Code Playgroud)
如果你有PHP 5.3或更高版本,你也可以使用匿名函数:
usort($array, function($a, $b) { return $b->id - $a->id; });
Run Code Online (Sandbox Code Playgroud)