Dcp*_*Dcp 1 php arrays sorting
我有一个包含一些像这样的对象的数组:
$user_list = [$user1, $user2, $user3];
Run Code Online (Sandbox Code Playgroud)
在哪里
$user1 = new User()
$user1->number = 3
$user1->name = 'Mike'
$user2 = new User()
$user2->number = 8
$user2->name = 'Alex'
$user3 = new User()
$user3->number = 5
$user3->name = 'John'
Run Code Online (Sandbox Code Playgroud)
我想从数组中检索具有最高number值的对象,如下所示:
// return $user2
$userWithMaxNumber = some_function($user_list)
Run Code Online (Sandbox Code Playgroud)
您可以对用户列表进行线性搜索,以找到数量最多的用户(请阅读代码注释以获取解释):
function get_highest($arr) {
$max = $arr[0]; // set the highest object to the first one in the array
foreach($arr as $obj) { // loop through every object in the array
$num = $obj->number; // get the number from the current object
if($num > $max->number) { // If the number of the current object is greater than the maxs number:
$max = $obj; // set the max to the current object
}
}
return $max; // Loop is complete, so we have found our max and can return the max object
}
print_r(get_highest($user_list));
Run Code Online (Sandbox Code Playgroud)
或者,为了产生更好的时间复杂度,您可以考虑将用户列表存储在最大堆中
| 归档时间: |
|
| 查看次数: |
2338 次 |
| 最近记录: |