首页 > 解决方案 > 不能在 Laravel 中使用 stdClass 类型的对象作为数组

问题描述

我收到以下错误:

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

查询生成器:

$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

标签: phpmysqldatabaselaravellaravel-blade

解决方案


该数据库查询返回一个Collection对象stdClass。它不返回Collection数组。调用toArrayCollection会给你一个stdClass对象数组。

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

推荐阅读