【问题标题】:Laravel Cannot use object of type stdClass as array with Job when iterating over data [duplicate]迭代数据时,Laravel 无法将 stdClass 类型的对象用作 Job 的数组 [重复]
【发布时间】:2025-12-26 20:45:07
【问题描述】:

我正在尝试遍历我的 Laravel 工作文件之一中的一些数据。我成功地获取了我的数据,并且可以在将其记录到文件时看到它,但是由于某些奇怪的原因,当我尝试使用 foreach 循环遍历我的数据时,我收到了这个错误:

不能使用 stdClass 类型的对象作为数组

public function handle()
{

  $filters = json_decode($this->report->discovery_filters);

  Log::debug($filters); // gives me my data which I'll attach

  foreach ($filters as $key => $findable) {

    Log::debug($findable['query']['table']); // errors
    die;

  }
}

我的数据:

[2021-03-10 14:11:57] local.DEBUG: array (
  0 => 
  (object) array(
     'name' => 'Sessions',
     'componentID' => 2435,
     'query' => 
    (object) array(
       'table' => 'data_google_analytics'

// etc... too much data to attach the rest, but 'query' and then 'table' clearly exists

我错过了什么?

【问题讨论】:

  • 要从 json 字符串中获取数组作为结果,您应该将第二个参数设置为布尔值 true。 $filters = json_decode($this->report->discovery_filters,true);

标签: php laravel query-builder


【解决方案1】:

错误告诉您问题所在:您正试图将对象用作数组。

相反,通过在 json_decode 中指定 true 作为第二个参数,强制将 JSON 解码为数组而不是数组和对象:

$filters = json_decode($this->report->discovery_filters, true);

这将强制 json_decode 将对象转换为关联数组。

【讨论】:

    最近更新 更多