2

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

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

我还有一个数组,其中包含第一个数组帖子 ID,按我喜欢显示该帖子的顺序排列。可以说数组映射是这样的:

[map] => Array
    (
        [0] => 4
        [1] => 21
        [2] => 100
        [3] => 1
    )

现在算式。我可以使用 Map 数组作为映射,根据每个对象 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
                ...
             )
    )
4

2 回答 2

2

PHP 有一个内置的方法来做到这一点,使用array_multisort函数:

$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

在这里试试:http: //codepad.org/5rqncj3B

于 2013-05-26T13:17:58.090 回答
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);
} 
于 2013-05-26T13:15:23.047 回答