以特定顺序对 PHP 中的对象数组进行排序 [英] Sorting an Array of Objects in PHP In a Specific Order

查看:38
本文介绍了以特定顺序对 PHP 中的对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PHP 中有两个数组.第一个数组 ($author_array) 由特定顺序的 user_ids 组成,如下所示:(8, 1, 6)

I have two arrays in PHP. The first array ($author_array) is comprised of user_ids in a particular order, like so: (8, 1, 6)

第二个数组 ($user_results) 由一个对象数组组成,如下所示:

The second array ($user_results) is comprised of an array of objects like so:

Array
(
    [0] => stdClass Object
        (
            [ID] => 1
            [user_login] => user1
        )
    [1] => stdClass Object
        (
            [ID] => 6
            [user_login] => user6
        )
    [2] => stdClass Object
        (
            [ID] => 8
            [user_login] => user8
        )
)

我想对第二个数组进行排序",使其按此顺序排列,它与 (8, 1, 6) 的第一个数组中的值的顺序相匹配.所以它看起来像这样:

I'd like to "sort" the second array so it's in this order, which matches the order of the values in the first array of (8, 1, 6). So it'd look like this:

Array
(
    [0] => stdClass Object
        (
            [ID] => 8
            [user_login] => user8
        )
    [1] => stdClass Object
        (
            [ID] => 1
            [user_login] => user1
        )
    [2] => stdClass Object
        (
            [ID] => 6
            [user_login] => user6
        )
)

我不擅长数据结构.我怎么能这样做?:-)

I'm weak on data structures. How could I do this? :-)

预先感谢您的帮助!

-鲍勃

推荐答案

使用 usort 并提供自定义比较功能它使用排序"数组中键的位置来确定排序顺序,例如类似:

Use usort and provide a custom comparison function which uses the position of the key in your "ordering" array to determine the sort order, e.g. something like:

function cmp($a, $b) 
{
   global $author_array;

   $pos1=array_search ($a->ID, $author_array);
   $pos2=array_search ($b->ID, $author_array);

   if ($pos1==$pos2)
       return 0;
   else
      return ($pos1 < $pos2 ? -1 : 1);

}


usort($user_results, "cmp");

这篇关于以特定顺序对 PHP 中的对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆