28

I'm using amazon product advertising api. Values are returned as a multidimensional objects.

It looks like this:

object(AmazonProduct_Result)#222 (5) {
  ["_code":protected]=>
  int(200)
  ["_data":protected]=>
  string(16538) 
array(2) {
    ["IsValid"]=>
    string(4) "True"
    ["Items"]=>
    array(1) {
      [0]=>
      object(AmazonProduct_Item)#19 (1) {
        ["_values":protected]=>
        array(11) {
          ["ASIN"]=>
          string(10) "B005HNF01O"
          ["ParentASIN"]=>
          string(10) "B008RKEIZ8"
          ["DetailPageURL"]=>
          string(120) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/B005HNF01O?SubscriptionId=AKIAJNFRQCIJLTY6LDTA&tag=*********-20"
          ["ItemLinks"]=>
          array(7) {
            [0]=>
            object(AmazonProduct_ItemLink)#18 (1) {
              ["_values":protected]=>
              array(2) {
                ["Description"]=>
                string(17) "Technical Details"
                ["URL"]=>
                string(217) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/tech-data/B005HNF01O%3FSubscriptionId%3DAKIAJNFRQCIJLTY6LDTA%26tag%*******-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB005HNF01O"
              }
            }
            [1]=>
            object(AmazonProduct_ItemLink)#17 (1) {
              ["_values":protected]=>
              array(2) {

I mean it also has array inside objects. I would like to convert all of them into a multidimensional array.

4
  • 1
    Why do you need this to be an array? many common array tasks (like foreach) can also be used with objects. Commented Nov 26, 2012 at 15:31
  • How to check value exists or not in objects? I've tried using isset but its not working. Commented Nov 26, 2012 at 15:45
  • Since its an object, the value should always exist. You should check if its set to something usable (or just null) Commented Nov 26, 2012 at 15:47
  • Thanks MrGlass. It works when I use it with is_null function. Thanks Commented Nov 26, 2012 at 15:55

6 Answers 6

148

I know this is old but you could try the following piece of code:

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

where $object is the response of the API.

Sign up to request clarification or add additional context in comments.

3 Comments

ps: binary values like pdfs or similar, using in soapClient response can be lost using this approach
While this solution works well, I'd really like to know why there is no native php method for this... This answer is 10 years old and I still can't find better way than this. Isn't there any modern way? Even if it does the same in the background, it's just obfuscating its functionality in code...
Or wait... Is get_object_vars($object) equivalent? See Quolonel Questions's answer
24

You can use recursive function like below:

function object_to_array($obj, &$arr)
{
 if (!is_object($obj) && !is_array($obj))
 {
  $arr = $obj;
  return $arr;
 }

 foreach ($obj as $key => $value)
 {
  if (!empty($value))
  {
   $arr[$key] = array();
   objToArray($value, $arr[$key]);
  }
  else {$arr[$key] = $value;}
 }

 return $arr;
}

4 Comments

You may need to make it to be neater
A slightly neater approach for this common request: function objectToArray($data) { if (is_object($data)) { $data = get_object_vars($data); } if (is_array($data)) { return array_map(FUNCTION, $data); } else { return $data; } }
hello @SubRed, your answer seems helpful to me! my query is what we have to pass in &$arr ?
hi @SagarPanchal var &$arr is your result variable. You can use it like this gist.github.com/anonymous/346f780acda292dea4cd. I hope it helps.
5
function convertObjectToArray($data) {
    if (is_object($data)) {
        $data = get_object_vars($data);
    }

    if (is_array($data)) {
        return array_map(__FUNCTION__, $data);
    }

    return $data;
}

Credit to Kevin Op den Kamp.

Comments

1

Just in case you came here as I did and didn't find the right answer for your situation, this modified version of one of the previous answers is what ended up working for me:

protected function objToArray($obj)
{
    // Not an object or array
    if (!is_object($obj) && !is_array($obj)) {
        return $obj;
    }

    // Parse array
    foreach ($obj as $key => $value) {
        $arr[$key] = $this->objToArray($value);
    }

    // Return parsed array
    return $arr;
}

The original value is a JSON string. The method call looks like this:

$array = $this->objToArray(json_decode($json, true));

Comments

1

I wrote a function that does the job, and also converts all json strings to arrays too. This works pretty fine for me.

function is_json($string) {
    // php 5.3 or newer needed;
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

function objectToArray($objectOrArray) {
    // if is_json -> decode :
    if (is_string($objectOrArray)  &&  is_json($objectOrArray)) $objectOrArray = json_decode($objectOrArray);

    // if object -> convert to array :
    if (is_object($objectOrArray)) $objectOrArray = (array) $objectOrArray;

    // if not array -> just return it (probably string or number) :
    if (!is_array($objectOrArray)) return $objectOrArray;

    // if empty array -> return [] :
    if (count($objectOrArray) == 0) return [];

    // repeat tasks for each item :
    $output = [];
    foreach ($objectOrArray as $key => $o_a) {
        $output[$key] = objectToArray($o_a);
    }
    return $output;
}

Comments

1

This is an old question, but I recently ran into this and came up with my own solution.

array_walk_recursive($array, function(&$item){
    if(is_object($item)) $item = (array)$item;
});

Now if $array is an object itself you can just cast it to an array before putting it in array_walk_recursive:

$array = (array)$object;
array_walk_recursive($array, function(&$item){
    if(is_object($item)) $item = (array)$item;
});

And the mini-example:

array_walk_recursive($array,function(&$item){if(is_object($item))$item=(array)$item;});

In my case I had an array of stdClass objects from a 3rd party source that had a field/property whose value I needed to use as a reference to find its containing stdClass so I could access other data in that element. Basically comparing nested keys in 2 data sets.

I have to do this many times, so I didn't want to foreach over it for each item I need to find. The solution to that issue is usually array_column, but that doesn't work on objects. So I did the above first.

2 Comments

hmm for some reason this code didn't work for an array I'm trying to convert even though it seems it should work. Haven't been able to figure out why. Here is a sample of the code: 3v4l.org/YRFLq
^ reduced the problem a bit: 3v4l.org/Vn6aH. Looks like objects with object properties doesn't work?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.