两个PHP数组 - 根据另一个数组的值顺序对一个数组进行排序

7

我有两个PHP数组,像这样:

  1. X条记录的数组,包含按特定顺序排列的WordPress帖子ID
  2. WordPress帖子的数组

这两个数组看起来像这样:

数组一(已排序的自定义WordPress帖子ID数组)

Array (  
  [0] => 54
  [1] => 10
  [2] => 4
)

数组二(WordPress文章数组)

Array ( 
    [0] => stdClass Object
        (
            [ID] => 4
            [post_author] => 1
    )
    [1] => stdClass Object
        (
            [ID] => 54
            [post_author] => 1
    )
    [2] => stdClass Object
        (
            [ID] => 10
            [post_author] => 1
    )
)

我希望按照第一个数组中的ID顺序对WordPress文章数组进行排序。
希望这样说起来有意义,非常感谢您的帮助。
汤姆
编辑:服务器运行的是PHP版本5.2.14。
3个回答

10

使用usort应该相当容易,它使用用户定义的比较函数对数组进行排序。结果可能类似于以下内容:

usort($posts, function($a, $b) use ($post_ids) {
    return array_search($a->ID, $post_ids) - array_search($b->ID, $post_ids);
});
请注意,此解决方案使用匿名函数和闭包,因此需要PHP 5.3。
在PHP 5.3之前(黑暗时代!),一个简单的解决方案是使用快速循环,然后使用ksort
$ret = array();
$post_ids = array_flip($post_ids);
foreach ($posts as $post) {
    $ret[$post_ids[$post->ID]] = $post;
}
ksort($ret);

我正在输入完全相同的解决方案,+1。 附言:我认为在此函数之前和之后需要使用array_flip $post_ids。 - Richard Tuin
@Richard Tuin 那将是一个解决方案 - 另一个是使用 array_search,正如我正在更正我的帖子所使用的那样。 - lonesomeday
这看起来是一个非常优雅的解决方案,但是当我尝试实现它时,我不明白函数应该做什么?如果我直接从这里复制,我会得到以下错误: 语法错误:意外的T_FUNCTION ---- 我觉得我应该创建一个函数来进行比较?(也抱歉我有误解...毫无疑问我正在经历一种障碍)...编辑:阅读 http://php.net/manual/en/function.usort.php 似乎让我清楚一点了,但还是被卡住了! - Tisch
@lonesomeday 看起来我使用的是 PHP 版本 5.2.14... 这可能解释了很多问题。真是太遗憾了,因为那看起来是一个不错且快速的解决方案。 - Tisch
2
你可以使用array_flip()代替array_search来解决5.3之前的问题,这对于排序大型列表会更好。 - goat
显示剩余4条评论

2

您可以创建一个嵌套循环机制,以匹配顺序和 ID,并重建一个新的帖子数组。

$new_post_array = array();

foreach($id_array as $id) {          //loop through custom ordered ids

    foreach($post_array as $post) {  //for every id loop through posts

        if($id == $post->ID){         //and when the custom ordered id matches the post->ID

            new_array[] = $post       //push the post on the new array

        }

    }

}

在这里复制两个数组(这就是foreach的作用)是不必要的。 - Richard Tuin
谢谢您的回答。这个方法可以实现,但是似乎有点慢?不过我还是接受了这个答案,因为它确实能够满足我的需求,并且可以在PHP 5.2中使用。 - Tisch
抱歉@jondavidjohn,我不得不切换到更快的解决方案。再次感谢您。 - Tisch

2
$sortOrderMap = array_flip($postIds);

usort($posts, function($postA, $postB) use ($sortOrderMap) {
    return $sortOrderMap[$postA->ID] - $sortOrderMap[$postB->ID];
});

你可以将b从a中减去,而不是将a从b中减去以实现反向排序。

谢谢您的回答。上面的解决方案非常相似,如果可能的话,我会尝试追求它。不过看起来 PHP 5.2 阻止了我 :) - Tisch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接