Sort Object in PHP

后端 未结 10 1368
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 01:51

What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.

$sortedObjectArary = sort($unsortedObjectArray, $Object-         


        
10条回答
  •  遥遥无期
    2020-11-29 02:28

    You could use the usort() function and make your own comparison function.

    $sortedObjectArray = usort($unsortedObjectArray, 'sort_by_weight');
    
    function sort_by_weight($a, $b) {
        if ($a->weight == $b->weight) {
            return 0;
        } else if ($a->weight < $b->weight) {
            return -1;
        } else {
            return 1;
        }
    }
    

提交回复
热议问题