Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Convert Object (With Protected Values) To Associative Array

If you need to quickly and easily convert an object to an associative array, the following is a simple solution:

1
$array = json_decode(json_encode($object), true);

In many cases - and if the above doesn't float your boat - you may simply typecast it:

1
$array =  (array) $object;

However, neither of the above solutions work with objects that contain protected and/or private values. In our case, we were trying to access protected header values from WP's wp_remote_get function. The following function will return an associative array with values accessible via traditional means.

1
<?php 
2
/*
3
    Convert Object (With Protected Values) To Associative Array
4
    http://www.beliefmedia.com/object-to-array
5
*/
6
 
7
 
8
function beliefmedia_objarray($object) {
9
    $reflectionClass = new ReflectionClass(get_class($object));
10
    $array = array();
11
    foreach ($reflectionClass->getProperties() as $property) {
12
        $property->setAccessible(true);
13
        $array[$property->getName()] = $property->getValue($object);
14
        $property->setAccessible(false);
15
    }
16
  return $array;
17
}

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment