PHP基于子对象值的短数组

时间:2013-05-26 13:02:46

标签: php arrays sorting

我有一个包含简单对象的数组。我看到的数组如下:

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

2 个答案:

答案 0 :(得分:2)

使用array_multisort函数,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

在此处试试:http://codepad.org/5rqncj3B

答案 1 :(得分: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);
}