Page 1 of 1

Recursively converting objects to arrays

Posted: Wed Jul 30, 2008 11:27 am
by jvdc
Hi!

I've got a little problem. I have an object that has other objects as its properties. Here's an example:

Code: Select all

 
Zend_Service_Amazon_Item Object
(
    [ASIN] => 0756629721
    [DetailPageURL] => http://www.amazon.com/Mesopotamia-Eyewi ... 0756629721
    [SalesRank] => 75655
    [SmallImage] => Zend_Service_Amazon_Image Object
        (
            [Url] => Zend_Uri_Http Object
                (
                )
            [Height] => 75
            [Width] => 58
        )
 
    [MediumImage] => Zend_Service_Amazon_Image Object
        (
            [Url] => Zend_Uri_Http Object
                (
                )
            [Height] => 160
            [Width] => 124
        )
    [LargeImage] => Zend_Service_Amazon_Image Object
        (
            [Url] => Zend_Uri_Http Object
                (
                )
            [Height] => 500
            [Width] => 387
        )
)
 
Now I want to convert this object into an array. If I use get_object_vars, it converts the primary properties of the object into an array, but not the secondary ones (like [SmallImage]). I've tried various ways of converting it to an array, both recursively and non-recursively, but I just can't get it to work... My latest try is this:

Code: Select all

 
           $book_array = get_object_vars($book);
            foreach ($book_array as &$entry) {
                if (is_object($entry)) {
                    $entry = get_object_vars($entry);
                }
            }
 
No luck... can anyone please help?

Also, can anyone tell me whether there is a way in Zend Cache to write objects to the cache?

Thanks a lot in advance!

Jan

Re: Recursively converting objects to arrays

Posted: Wed Jul 30, 2008 1:20 pm
by infolock
Not to seem too picky, but why would you do this? I'm curious because if the object has all the properties and values you need, why create more overhead by re-creating the same object structure into an array?

Re: Recursively converting objects to arrays

Posted: Wed Jul 30, 2008 1:57 pm
by jvdc
I want to cache the amazon books. I'm using Zend Cache, and I can't get it to cache an object.

Re: Recursively converting objects to arrays

Posted: Thu Jul 31, 2008 2:07 pm
by infolock
well, the object i think you are refering to is a dynamic object that retrieves the data from an RSS feed or the like. In this case, the data should always be dynamic. If you want to cache it, i would recommend putting it into a database and only checking for new books after x amount of time (or you could even store the results to your own XML file and use it the RSS feed).

As for the array portion, just loop through the object and store each portion to a key value pair for a new array. that's about the easiest way to get what you want.