【问题标题】:Sorting stdClass Object in two将stdClass对象一分为二
【发布时间】: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


【解决方案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谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2011-03-15
    • 2015-08-20
    • 1970-01-01
    • 2011-11-08
    相关资源
    最近更新 更多