我如何在PHP中排序以下数组/ stdclass对象?

这个问题在这里已有答案:            >            Sort array of objects by object fields                                    16个
如何在php中用’pos’对这个对象进行排序?

Array ( 
[0] => stdClass Object ( [str] => Mondays [pos] => 170 ) 
[1] => stdClass Object ( [str] => Tuesdays [pos] => 299 )
[2] => stdClass Object ( [str] => Wednesdays [pos] => 355 )
[3] => stdClass Object ( [str] => Thursdays [pos] => 469 )
[4] => stdClass Object ( [str] => Fridays [pos] => 645 )
[5] => stdClass Object ( [str] => Mondays [pos] => 972 )
[6] => stdClass Object ( [str] => Tuesdays [pos] => 1033 ) 
[7] => stdClass Object ( [str] => Thursdays [pos] => 1080 )
[8] => stdClass Object ( [str] => Fridays [pos] => 1180 ) 

)

您可以使用usort()系列函数在str或pos上对其进行排序.你必须为此定义自己的比较功能.

伪PHP示例:

function compareItems($a, $b)
{
    if ( $a->pos < $b->pos ) return -1;
    if ( $a->pos > $b->pos ) return 1;
    return 0; // equality
}

uasort($yourArray, "compareItems");

根据您的需要,other comparison functions可能更合适.

https://stackoverflow.com/questions/2146749/how-do-i-sort-the-following-array-stdclass-object-in-php

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:我如何在PHP中排序以下数组/ stdclass对象?