我有下面的数组,已经从wordpress使用get_children()生成。问题是,它似乎不能按照wordpress中使用的菜单顺序来排序输出。
所以下面的数组需要按键[menu_order]的内部值排序。我已经尝试了很多不同的方法使用ussort等,但似乎不能让它工作。
Array
(
[40] => WP_Post Object
(
[ID] => 40
[post_author] => 1
[post_date] => 2016-09-03 19:31:25
[post_date_gmt] => 2016-09-03 19:31:25
[post_content] => test 2
[post_title] => Test 2
[post_excerpt] =>
[post_status] => publish
[comment_status] => closed
[ping_status] => closed
[post_password] =>
[post_name] => test-2
[to_ping] =>
[pinged] =>
[post_modified] => 2016-09-03 19:56:04
[post_modified_gmt] => 2016-09-03 19:56:04
[post_content_filtered] =>
[post_parent] => 2
[guid] => http://example.com/2
[menu_order] => 2
[post_type] => page
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
[38] => WP_Post Object
(
[ID] => 38
[post_author] => 1
[post_date] => 2016-09-03 19:23:18
[post_date_gmt] => 2016-09-03 19:23:18
[post_content] => test 1
[post_title] => Test 1
[post_excerpt] =>
[post_status] => publish
[comment_status] => closed
[ping_status] => closed
[post_password] =>
[post_name] => test-1
[to_ping] =>
[pinged] =>
[post_modified] => 2016-09-03 19:51:17
[post_modified_gmt] => 2016-09-03 19:51:17
[post_content_filtered] =>
[post_parent] => 2
[guid] => http://example.com/1
[menu_order] => 1
[post_type] => page
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
)
虽然您可以将usort
与回调一起使用,但正确的解决方案是请求通过get_children()
直接订购的商品。您可以通过使用orderby
参数来实现这一点。这样的:
$children = get_children(array(
// other args here
'orderby' => 'menu_order'
));
详细信息请参见WordPress的get_children()和get_posts()
这是usort
的典型用例
usort($array, function($a, $b){
return $a['menu_order'] > $b['menu_order'];
});
您可以使用ussort: http://php.net/usort。我试着使它更详细如下。
function menu_order($a, $b)
{
return strcmp($a->menu_order, $b->menu_order);
}
usort($newsortedarray, "menu_order");
foreach ($newsortedarray as $array){
// continue....
}