首页 > 解决方案 > 迭代数据时,Laravel 无法将 stdClass 类型的对象用作 Job 的数组

问题描述

我正在尝试遍历我的 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

我错过了什么?

标签: phplaravelquery-builder

解决方案


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

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

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

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


推荐阅读