如何通过stdClass对象中的公共元素对stdClass对象数组进行排序?

时间:2016-07-07 03:28:06

标签: php arrays iteration

如何在PHP中按降序排列[sequence_number]的以下数组?

Array
(
    [0] => stdClass Object
        (
            [debate_id] => 1
            [stakeholder_id] => 1
            [sequence_number] => 1
            [title] => SLIDE 1 - STAKEHOLDER 1
            [content] => This is the first slide for STAKEHOLDER 1
        )

    [1] => stdClass Object
        (
            [debate_id] => 1
            [stakeholder_id] => 1
            [sequence_number] => 4
            [title] => SLIDE 2 - STAKEHOLDER 1
            [content] => This is the second slide for STAKEHOLDER 1
        )

    [2] => stdClass Object
        (
            [debate_id] => 1
            [stakeholder_id] => 1
            [sequence_number] => 3
            [title] => SLIDE 3 - STAKEHOLDER 1
            [content] => This is the third slide for STAKEHOLDER 1
        )

)

2 个答案:

答案 0 :(得分:2)

试试这个:

usort($array, function($obj1, $obj2) {
    return $obj2->sequence_number - $obj1->sequence_number;
});

答案 1 :(得分:2)

您可以使用usort,以下是如何为您的示例执行此操作:

function compare_func($a, $b)
{
    if ($a->sequence_number == $b->sequence_number) {
        return 0;
    }
    return ($a->sequence_number < $b->sequence_number) ? -1 : 1;
    // You can apply your own sorting logic here.
}

usort($arrayOfObjects, "compare_func");
  

usort()函数使用用户提供的比较函数按其值对数组进行排序。

在我们的案例中, compare_func 是我们用户提供的功能。

如果要按字符串值对数组进行排序,可以在用户提供的函数中使用strcmp()函数。像这样,

return strcmp($a["title"], $b["title"]);

参考:http://php.net/manual/en/function.usort.php