0

I'm trying to loop over some data in one of my Laravel's job files. I'm successfully able to get my data, and can see it when I log it to a file, but for some strange reason when I try to iterate over my data with a foreach loop, I'm getting this error:

Cannot use object of type stdClass as array

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;

  }
}

My data:

[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

What am I missing?

Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • 1
    To get an array as result from a json string you should set second param as boolean true. `$filters = json_decode($this->report->discovery_filters,true);` – Basharmal Mar 10 '21 at 14:22

1 Answers1

0

The error’s telling you what the problem is: you’re trying to use an object as an array.

Instead, force the JSON to be decoded to arrays rather than arrays and objects by specifying true as the second parameter in json_decode:

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

This will force json_decode to turn objects into associative arrays instead.

Basharmal
  • 1,313
  • 10
  • 30