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

时间:2018-12-22 13:57:09

标签: php arrays sorting

我有一个数组,其中包含一些这样的对象:

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

其中

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

我想从具有最高number值的数组中检索对象 像这样:

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

3 个答案:

答案 0 :(得分:2)

您可以linear-search浏览用户列表,以找到数量最大的用户(阅读代码注释进行解释):

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

或者,对于时间复杂度更高的内容,您可以考虑将用户列表存储在max-heap

答案 1 :(得分:1)

简单:

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

输出:

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

Sandbox

仅注意这部分是实际功能:

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

其余的只是设置,但我认为最好发布完整的工作示例,然后再对此进行解释。

这是未压缩的代码:

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

这是相当困难的事情,我们做数组归约。如果$v的值大于携带项目$c,我们将携带项目设置为$v。如果没有,我们只退还携带物品。最后,我们剩下一个具有最大值的项目。

如果您想要更多的保证和鲁棒性,可以键入hint回调的参数以仅接受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
);

这将我们绑定到用户类API或接口。这样可以确保仅接受用户对象,因此我们可以减少错误检查,因为我们知道它是什么类型的对象以及它具有什么方法...

但是,几乎无论您做什么,都必须至少遍历整个数组一次以“发现”所有值。

答案 2 :(得分:0)

另一种选择是将用户添加到阵列,并通过->number将用户usort添加到阵列。然后从数组中获取第一项:

$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

请注意,usort会使$users数组发生突变,因此原始顺序会发生变化(除非开头的顺序已经正确)

相关问题