PHP 基于子对象值的短数组

标签 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
    )

现在是方程式。我可以根据每个对象 ID 属性,使用 Map 数组作为映射来排序包含对象的数组,以获得如下所示的结果:

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

最佳答案

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

关于PHP 基于子对象值的短数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16759490/

相关文章:

C++ 在快速排序函数中获取 StackOverflow 错误

php - 获取在 PHP 中重定向的远程图像

php - 多个 "agents"处理单个数组

c++ - 将 long 复制到 unsigned char 数组的后半部分

c - 对于数组,为什么 a[5] == 5[a]?

c# - 如何按数组中指定索引处的元素对数组列表进行排序

mysql - wordpress custom_meta 时间戳排序

php - 如何在 laravel 中使用 sql NOW( ) 函数

php - 动态表单并循环表单数组插入Mysql

php - Apache wildcard SSL cert for wildcard vhost and specifically named vhost