gpt4 book ai didi

php - 将具有特定值的数组元素移动到数组顶部

转载 作者:行者123 更新时间:2023-12-03 18:36:01 25 4
gpt4 key购买 nike

我有一个与此类似的数组:

Array
(
[0] => stdClass Object
(
[Leasing] => 12939.74
[Name] => Jeremy
[Rental] => 0
[Sales] => 56603.13
[Total] => 69542.87
)
[1] => stdClass Object
(
[Leasing] => 0
[Name] => Shaun
[Rental] => 0
[Sales] => 58590
[Total] => 58590
)
[2] => stdClass Object
(
[Leasing] => 0
[Name] => Lindsay
[Rental] => 0
[Sales] => 22951.97
[Total] => 22951.97
)
[3] => stdClass Object
(
[Leasing] => 0
[Name] => Sally
[Rental] => 1200
[Sales] => 21624.9
[Total] => 22824.9
)
[4] => stdClass Object
(
[Leasing] => 0
[Name] => House
[Rental] => 0
[Sales] => 16235.81
[Total] => 16235.81
)
[5] => stdClass Object
(
[Leasing] => 5298.85
[Name] => Bill
[Rental] => 1200
[Sales] => 0
[Total] => 6498.85
)
)

目前,数组使用以下方法按总数排序:
usort($data, function ($a, $b) {
return $b->Total - $a->Total;
});

现在,我需要能够始终将 [Name] => House 的人放在数组的顶部。我的想法是我可以让它按 Total 排序(因为我仍然需要那样),然后将带有 House 值的元素放在数组的开头。我可以选择一个特定的 KEY 并将其放在顶部,但 KEY 的值可能会根据谁的总数最高而发生变化。如何始终将名为 House 的人放在数组的顶部?

最佳答案

这应该有效:

usort($data, function ($a, $b) {
if ($a->Name != "House" && $b->Name == "House") {
return 1;
} elseif ($a->Name == "House" && $b->Name != "House") {
return -1;
} else {
return $b->Total - $a->Total;
}
});

来自 PHP: usort - Manual :

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.



在这种情况下,return 1 告诉排序函数 House 大于任何其他值, -1 告诉排序函数 House 小于任何其他值。

关于php - 将具有特定值的数组元素移动到数组顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14405909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com