【问题标题】:PHP usort comparison functionPHP usort比较函数
【发布时间】:2012-02-14 15:15:05
【问题描述】:

我使用 array_merge 合并了两个数组,现在需要按字母顺序对它们进行排序。问题是我需要比较两个不同的键,

例如

[0] => stdClass Object
(
[id] => 16
[title] => Oranges
)

[1] => stdClass Object
(
[id] => 23
[title] => Apples
)

[2] => stdClass Object
(
[id] => 16
[name] => Bananas
)

我需要比较“名称”属性以及“标题”属性,然后按字母顺序对它们进行排序(忽略 id),这样我的结果将是:

苹果
香蕉
橘子

但是,我这里的功能:

function compareItems($a, $b)
{
if ( $a->title < $b->title ) return -1;
if ( $a->title > $b->title ) return 1;
if ( $a->name < $b->name ) return -1;
if ( $a->name > $b->name ) return 1;
return 0;
}

usort($array, "compareItems");

...不合并,而是对一组属性(标题)然后另一组(名称)进行排序,从而给我:

苹果
橙子
香蕉

我希望我可以修改此函数以将两者合并在一起 - 我不是真正的 PHP 程序员,因此非常感谢任何帮助!

提前致谢。

【问题讨论】:

    标签: php arrays function object sorting


    【解决方案1】:

    我下面的比较功能应该适合你:

    function compareItems($a, $b)
    {
        $x = isset($a->title) ? $a->title : $a->name;
        $y = isset($b->title) ? $b->title : $b->name;
        return strcmp($x, $y);
    }
    

    【讨论】:

    • @RT:很高兴能帮上忙!请记住通过单击绿色复选标记将此问题标记为已回答。
    猜你喜欢
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多