如果有一个特定的键,如何重新排序数组元素


How to re-order array elements if there is a specific key?

似乎Wordpress wp_query没有提供按postrongtatus排序的选项。我想在其他帖子之前列出私人帖子。posts数组看起来像这样:

$posts = array(
             0=>object{
                     ....
                },
             1=>object{
                     ....
               },
            ....
         );

每个post对象都有一个'postrongtatus'键。如果值是'private',我想将帖子移动到数组的开头。如何?

使用usort():

usort($posts, ($a, $b) {
    return ($a->post_status < $b->post_status) ? -1 : 1;
});

看一下uasort()。这允许您编写自己的比较函数,并根据需要对数组进行排序。