简体   繁体   English

获取PHP数组中具有最高属性值的对象

[英]Get object with the highest property value in PHP array

I have an array with some objects like this: 我有一个包含这样的对象的数组:

$user_list = [$user1, $user2, $user3];

where 哪里

$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'

I would like to retrieve the object from array with the highest number value with something like: 我想检索最高数组对象number与类似值:

// return $user2
$userWithMaxNumber = some_function($user_list)  

You could linear-search through your list of users to find the one with the max number (read code comments for explanation): 您可以线性搜索用户列表以找到具有最大数量的用户(阅读代码注释以进行说明):

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));

Or, for something which yields better time complexity you may consider storing your list of users in a max-heap 或者,对于产生更好时间复杂度的事物,您可以考虑将用户列表存储在最大堆中

Simple: 简单:

//setup
class user{
    public $number;
}
//init
$user1 = new user();
$user1->number = 3;

$user2 = new user();
$user2->number = 8;

$user3 = new user();
$user3->number = 5;

$a = [$user1, $user2, $user3];
$max = 0;

//execute 
$o = array_reduce($a,function($c,$v){return$c->number<$v->number?$v:$c;},new user);

//output
print_r($o);

Output: 输出:

user Object
(
    [number:protected] => 8
)

Sandbox 砂箱

Note only this part is the actual function: 请注意,这部分是实际功能:

$o = array_reduce($a,function($c,$v){return$c->number<$v->number?$v:$c;},new user);

The rest is just setup, but I think it is better to post the full working example and then explain off of that. 其余的只是设置,但我认为最好发布完整的工作示例,然后解释。

Here is the code uncompressed: 这是未压缩的代码:

$o = array_reduce(
    $a,
    function($c,$v){
        return $c->number < $v->number ? $v : $c;
    },
    new user  //init a new user object for $c's initial value,  number = null
);

It's pretty strait forward, we do array reduce. 这是相当紧张的前进,我们做阵列减少。 If $v has a value greater then the carried item $c , we set the carried item to $v . 如果$v的值大于持有的项目$c ,我们将持有的项目设置为$v If not we just return the carried item. 如果不是,我们只返回持有物品。 And in the end, we are left with one item that has the max value. 最后,我们留下了一个具有最大值的项目。

If you wanted a bit more assurance and robustness, you can type hint the arguments of the callback to only accept user type objects: 如果您想要更多的保证和健壮性,可以键入提示回调的参数以仅接受user类型对象:

$o = array_reduce(
    $a,
    function(user $c, user $v){
        return $c->number < $v->number ? $v : $c;
    },
    new user  //init a new user object for $c's initial value,  number = null
);

This binds us to the user classes API or interface. 这将我们绑定到用户类API或接口。 Which insures that only user objects are accepted, so we can reduce our error checks as we know what type of object it is, and what methods it has... 这确保只接受用户对象,因此我们可以减少错误检查,因为我们知道它是什么类型的对象,以及它有什么方法......

But, pretty much no matter what you do you have to iterate over the entire array at least one time to "discover" all the values. 但是,无论你做什么,你必须至少在整个阵列上迭代一次以“发现”所有的值。

Another option could be to add the users to an array and usort the array by ->number . 另一选项可以是将用户添加到阵列和usort通过阵列->number Then get the first item from the array: 然后从数组中获取第一项:

$users = [$user1, $user2, $user3];

usort($users, function($a, $b){
    return $a->number < $b->number;
});

var_dump($users[0]);
print_r($users[0]->number); // 8

Php demo Php演示

Note that usort mutates the $users array, so the original order changes (Except when it is already in the right order at the beginning) 请注意,usort会改变$users数组,因此原始顺序会发生变化(除非它在开头时已经是正确的顺序)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM