【问题标题】:Max value in Array (StdClass error)数组中的最大值(StdClass 错误)
【发布时间】:2026-02-16 18:15:01
【问题描述】:

$gameAPI->游戏

"games": [
        {
            "appid": 10,
            "playtime_forever": 32
        },
        {
            "appid": 20,
            "playtime_forever": 0
        },
        {
            "appid": 30,
            "playtime_forever": 0
        },
        ]

我想获取appid + playtime_forever 数据,其中playtime_forever 在列表中具有最高值。

我使用了以下代码:

$data = array_reduce($data, function ($a, $b) {
    return @$a['playtime_forever'] > $b['playtime_forever'] ? $a : $b;
});

其中 $data = $gameAPI->游戏;

但是我得到了以下错误:不能使用 stdClass 类型的对象作为数组。上线:

return @$a['playtime_forever'] > $b['playtime_forever'] ? $a : $b;

【问题讨论】:

    标签: php arrays string loops


    【解决方案1】:

    正如您的错误所述,您将对象用作数组。要在 PHP 中访问对象属性,请使用箭头符号 ->:

    return $a->playtime_forever > $b->playtime_forever ? $a : $b;
    

    【讨论】: