简体   繁体   中英

Cannot use object of type stdClass as array in Laravel

I got the following error:

PHP Fatal error: Cannot use object of type stdClass as array in C:\\xampp\\htdocs\\enginepoker2\\storage\\framework\\views\\10cbbd076bede57a96e59c43af0e1b9e022b4a69.php on line 115

The query builder:

$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();

The Blade that gets the error:

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

That DB query returns a Collection of stdClass objects. It does not return a Collection of arrays. Calling toArray on that Collection will give you an array of stdClass objects.

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

The error is born from a misuse of the array itself. Try the following:

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

EDIT : The $statsMoneyInPlay is an array of objects, so the proper way to access it would be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM