Can't turn an object into an array.

Published 5 months ago by ChrisF79

Just starting to work on something and I have the following code:

class ProcessRetsListings
{

    public function __construct($results)
    {
        $this->results = $results;
    }

    public function process($results)
    {
        $results->toArray();
        foreach ($results as $result)
        {
            echo $result['StreetName'];
        }
    }
}

I ran a php gettype($results) and it is in fact an object. I try to turn it into an array and I get the error: Call to undefined method App\Models\RetsFeedApiResult::toArray()

I need it to be an array so I can work with it and ultimately save the entire result to the database.

Cronix
Cronix
5 months ago (798,990 XP)

->toArray() only works on certain laravel objects, like models, not php objects in general.

You could try just typecasting it to an array, but you'd only get visible (public) properties.

$results = (array) $results;
biishmar

@ChrisF79 did u try collection method?

$result = collect($result)->toArray();
jimmck

This object has private, protected or public data members only a constructor which takes an array and a method to iterate the array.

spekkionu

What does the RetsFeedApiResult class look like? Unless it is a simple object with public properties you will likely have to write your own toArray method.

Snapey
Snapey
5 months ago (1,044,305 XP)

I need it to be an array so I can work with it

Why? Just because that is familar? PHP works very well with objects

ChrisF79

Thanks everyone. @Snapey, main reason is because I think I can just insert it right into the DB.

jlrdw
jlrdw
5 months ago (252,700 XP)

It is just


$whatever = $row->whatever;

// Instead of

$whatever = $row->['whatever'];
Snapey
Snapey
5 months ago (1,044,305 XP)

The class would need to implement a toArray() method, but I'm guessing you cannot modify it?

Please sign in or create an account to participate in this conversation.