无法在Laravel中将stdClass类型的对象用作数组

时间:2018-10-02 03:37:03

标签: php mysql database laravel laravel-blade

我遇到以下错误:

  

PHP致命错误:无法在第115行的C:\ xampp \ htdocs \ enginepoker2 \ storage \ framework \ views \ 10cbbd076bede57a96e59c43af0e1b9e022b4a69.php中将stdClass类型的对象用作数组

查询构建器:

$statsMoneyInPlay = DB::table('enginepoker_log.poker')
    ->select(
        DB::raw("UNIX_TIMESTAMP(Date(ts)*100) as timestamp"),
        DB::raw("SUM(pot + p1pot + p2pot + p3pot + p4pot + p5pot + p6pot + p7pot + p8pot + p9pot) / count(*) As moneyInPlay")
    )
    ->groupBy(DB::raw("DATE(ts)"))
    ->orderByRaw("DATE(ts)")
    ->get()
    ->toArray();

出现错误的刀片服务器:

@php
    foreach ($statsMoneyInPlay as $key => $value) {
        echo "[".$value[0].", ".$value[1]."],";
    }
@endphp

2 个答案:

答案 0 :(得分:4)

该数据库查询返回Collection个对象中的一个stdClass个对象。它不返回Collection数组。在该toArray上调用Collection将为您提供stdClass对象的数组。

@foreach ($statsMoneyInPlay as $value)
    [ {{ $value->timestamp }}, {{ $value->moneyInPlay }} ],
@endforeach

答案 1 :(得分:0)

该错误源于对数组本身的滥用。请尝试以下操作:

foreach($statsMoneyInPlay as $stat) {
  echo "[" . $stat['timestamp'] . ", " . $stat['moneyInPlay'] . "]";
}

编辑$statsMoneyInPlay是一个对象数组,因此访问它的正确方法是:

foreach($statsMoneyInPlay as $stat) {
  echo "[" . $stat->timestamp . ", " . $stat->moneyInPlay . "]";
}