按内部值排序PHP数组

时间:2016-09-03 20:20:29

标签: php arrays wordpress

我有以下使用get_children()从wordpress生成的数组。问题是它似乎无法通过wordpress中使用的菜单顺序对输出进行排序。

因此,波纹管数组需要按键[menu_order]的内部值进行排序。我尝试了许多使用usort等的方法,但似乎无法使用它。

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
    )
)

3 个答案:

答案 0 :(得分:1)

虽然您可以使用usort进行回调,但正确的解决方案是请求通过get_children()直接订购的商品。您可以使用orderby参数来实现此目的。像这样:

$children = get_children(array(
  // other args here
  'orderby' => 'menu_order'
));

有关详细信息,请参阅WordPress“get_children()get_posts()

答案 1 :(得分:0)

这是usort

的典型用例
usort($array, function($a, $b){
    return $a['menu_order'] > $b['menu_order'];
});

答案 2 :(得分:0)

您可以使用usort: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....

 }