27

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.

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

6 Answers6

146

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.

kendepelchin
  • 2,680
  • 2
  • 21
  • 25
  • 1
    ps: binary values like pdfs or similar, using in soapClient response can be lost using this approach – celsowm Jan 22 '20 at 04:06
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;
}
John
  • 1
  • 13
  • 98
  • 177
SubRed
  • 3,169
  • 1
  • 18
  • 17
  • You may need to make it to be neater – SubRed Nov 26 '12 at 16:11
  • 6
    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; } } – Kevin Op den Kamp Mar 21 '14 at 10:16
  • hello @SubRed, your answer seems helpful to me! my query is what we have to pass in `&$arr` ? – SagarPPanchal Jul 17 '14 at 06:58
  • 1
    hi @SagarPanchal var &$arr is your result variable. You can use it like this https://gist.github.com/anonymous/346f780acda292dea4cd. I hope it helps. – SubRed Jul 18 '14 at 07:13
4
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.

Quolonel Questions
  • 6,603
  • 2
  • 32
  • 33
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));
Ixalmida
  • 603
  • 5
  • 15
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;
}
Amin Adel
  • 970
  • 3
  • 17
  • 33
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.

Cave Johnson
  • 6,499
  • 5
  • 38
  • 57
ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • 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: https://3v4l.org/YRFLq – Cave Johnson Oct 13 '20 at 18:34
  • ^ reduced the problem a bit: https://3v4l.org/Vn6aH. Looks like objects with object properties doesn't work? – Cave Johnson Oct 13 '20 at 18:40