【发布时间】:2022-01-28 09:49:45
【问题描述】:
我想按“terminland_days”值对团队列表进行排序
我在 Stack Overflow https://stackoverflow.com/a/38237197/5006328 中读到了同样的问题,但对此仍有疑问。
这是我的 PHP (PHP >=7.4) 代码:
public function display($tpl = null) {
// myval get from other model
//print_r ($myval);
$myval = Array
(
[0] => stdClass Object
(
[id] => 1
[state] => 1
[teams] => {"teams0":{"name":"Jhon","terminland_days":"3"},"teams1":{"name":"Alex","terminland_days":"2"}}
[distance] => 5839.5147520164
)
[1] => stdClass Object
(
[id] => 2
[state] => 1
[teams] => {"teams0":{"name":"Jeff","terminland_days":"12"},"teams1":{"name":"Fred","terminland_days":"1"}}
[distance] => 5839.5147520164
)
);
foreach ($myval as $item) {
$paramsteam = json_decode($item->teams);
foreach ($paramsteam as $team) {
// i want sorting Teams as "terminland_days" value
usort($team, "compare_func");
// error ==> Warning: usort() expects parameter 1 to be array, object given
echo $team->terminland_days;
}
}
}
public function compare_func($a, $b)
{
if ($a->terminland_days == $b->terminland_days) {
return 0;
}
return ($a->terminland_days < $b->terminland_days) ? -1 : 1;
// You can apply your own sorting logic here.
}
据我所知,我必须使用usort,请帮助我怎么做?
当print_r ($team);输出:
stdClass Object
(
[name] => Jhon
[terminland_days] => 3
)
stdClass Object
(
[name] => Alex
[terminland_days] => 2
)
stdClass Object
(
[name] => Jeff
[terminland_days] => 12
)
stdClass Object
(
[name] => Fred
[terminland_days] => 1
)
【问题讨论】:
-
请分享更多细节。 究竟是什么不适用于给定的代码?您尝试过什么来解决问题?
-
另外,你能分享一个可运行的代码示例吗?
$team包含什么? -
@NicoHaase 我将
print_r ($team);输出放在问题帖子上。请检查。谢谢 -
好吧,那么问题就很明显了:
usort对数组进行排序。对单个对象进行排序有什么意义? -
@NicoHaase 那么您对解决问题的建议是什么?
标签: php arrays foreach stdclass usort