按一个键对对象数组进行排序和搜索

时间:2012-08-19 21:51:59

标签: php arrays search sorting

$data = Array ( 
           [0] => stdClass Object ( [ID] => 1 [top_level] => gold [sub_level] => coal ) 
           [1] => stdClass Object ( [ID] => 3 [top_level] => bronze [sub_level] => dirt ) 
           [2] => stdClass Object ( [ID] => 4 [top_level] => silver [sub_level] => aluminum ) 
    )

使用PHP,我如何通过[sub_level]升序(或降序)来排序以产生以下内容?

Array ( 
       [0] => stdClass Object ( [ID] => 4 [top_level] => silver [sub_level] => aluminum ) 
       [1] => stdClass Object ( [ID] => 1 [top_level] => gold [sub_level] => coal ) 
       [2] => stdClass Object ( [ID] => 3 [top_level] => bronze [sub_level] => dirt )  
)

此外,搜索[sub_level]特定值的最有效方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以使用usort。在函数中,比较所需的两个属性并返回适当的值。有关详细信息,请参阅suggested duplicate