将 stdClass 对象一分为二

Sorting stdClass Object in two

我想按“terminland_days”值对 Teams 列表进行排序

我在 Stack Overflow 中读到了同样的问题,但仍然有问题。

这是我的 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
)

经过几个小时的推敲,我发现最好的办法是先把对象转成数组,然后再排序。所以:

$paramsteam = json_decode($item->teams,true);
usort($paramsteam, function ($item1, $item2) {
return $item1['terminland_days'] <=> $item2['terminland_days'];
});
foreach ($paramsteam as $team) {
    
    echo $team['terminland_days'];
    
}

@Nico haase谢谢