0

I have a string (JSON type), i wanted to convert it to PHP Array.

{  
   "action":"putEntity",
   "dataPacket":{  
      "entity":[  
         {  
            "name":"product",
            "data":[  
               {  }
            ]
         }
      ]
   }
}

I did following to do so,

$array = json_decode(json_encode($data), True);

When i do var_dump($array); it displays:

string(1578) "{ "action": "putEntity", "dataPacket": { "entity": [{ "name": "product", "data": [{ }] }] } }"

But when i do, print_r($array); it displays:

{
   "action": "putEntity",
   "dataPacket":{
   "entity":[
         {
         "name": "product",
         "data":[{}]
         }
      ]
   }
}

Issue is when i try to print $array['dataPacket']; it throws error illegal string offset 'dataPacket'

why var_dump is showing it as String? please help.

4
  • Are you looping through the JSON array and then outputting it's results?
    – Adam
    Commented Apr 6, 2018 at 12:26
  • 1
    Are you... encoding the (already encoded) string and then decoding one layer, thus giving you back the original (encoded) string? Commented Apr 6, 2018 at 12:27
  • var_dump is showing it as a string as it is a string at that moment. If it is valid json you can decode it and then you can access $array['dataPacket']. Exact debugging is hard without your full code.
    – Blackbam
    Commented Apr 6, 2018 at 12:28
  • Actually, print_r() is also saying it's a string. If it were an array, its output would be along the lines of Array ( [action] => putEntity etc. Commented Apr 6, 2018 at 12:44

1 Answer 1

1
$array = json_decode(json_encode($data), True);

Should be

$array = json_decode($data, true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.