phparraysforeachstdclassusort

Sorting stdClass Object in two


I want sorting Teams list by "terminland_days" value

I read same question in Stack Overflow https://stackoverflow.com/a/38237197/5006328 but still have problem on this.

This is my PHP (PHP >=7.4) code:

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.
}
    

as I understand, I must use usort, please help me how I can do it?

When print_r ($team); output:

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
)

Solution

  • After a few hours of scrutiny, I realized that the best way was to first convert the object to an array and then sort it. so :

    $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'];
        
    }
    

    also @Nico haase thank you