基于子对象值的PHP短数组

基于子对象值的PHP短数组,php,arrays,sorting,Php,Arrays,Sorting,我有一个包含简单对象的数组。我拥有的阵列如下所示: [posts] => Array ( [0] => WP_Post Object ( [ID] => 4 [post_title] => Post #4 ... ) [1] => WP_Post Object

我有一个包含简单对象的数组。我拥有的阵列如下所示:

[posts] => Array
    (
        [0] => WP_Post Object
            (
                [ID] => 4
                [post_title] => Post #4
                ...
             )
        [1] => WP_Post Object
            (
                [ID] => 100
                [post_title] => Post #100
                ...
             )
        [2] => WP_Post Object
            (
                [ID] => 1
                [post_title] => Post #1
                ...
             )
        [3] => WP_Post Object
            (
                [ID] => 21
                [post_title] => Post #21
                ...
             )
    )
另外,我还有一个数组,它包含第一个数组posts ID,其顺序与我希望显示posts的顺序相同。假设数组映射如下所示:

[map] => Array
    (
        [0] => 4
        [1] => 21
        [2] => 100
        [3] => 1
    )
现在是方程式。我是否可以基于每个对象ID属性,通过使用映射数组作为映射,对包含对象的数组进行排序,以获得如下结果:

[posts] => Array
    (
        [0] => WP_Post Object
            (
                [ID] => 4
                [post_title] => Post #4
                ...
             )
        [1] => WP_Post Object
            (
                [ID] => 21
                [post_title] => Post #21
                ...
             )
        [2] => WP_Post Object
            (
                [ID] => 100
                [post_title] => Post #100
                ...
             )
        [3] => WP_Post Object
            (
                [ID] => 1
                [post_title] => Post #1
                ...
             )
    )

我的解决方案可能效率不高,但很简单:

function find_post_by_id($posts, $id) {
  foreach($posts as $post) {
    if ($post->id == $id) {
      return $post;
    }
  }
  // error handling here
}

$sorted_posts = array();
foreach($map as $id) {
  $sorted_posts[] = find_post_by_id($posts, $id);
} 

PHP有一种内置的方法来实现这一点,使用以下函数:

$col = array();
foreach ($posts as $post) {
    $col[] = array_search($post->ID, $map);
}

array_multisort($col, $posts);

// now $posts is sorted in the order specified in $map

在此处尝试:

检查提供回调的排序函数,看看这是否有助于数组最初来自何处?我将从这里开始,看看是否有可能修改该代码,使其首先使用post id作为数组键。这是WordPress在使用WP_查询时生成的数组。如果运行WP\u查询并打印结果,您将找到我在上面使用的数组