eqiz eqiz - 3 months ago 8
PHP Question

Read through dynamic JSON in php

I'm needing to know how to read through JSON in PHP that I don't know the key's for. Here is an example of a json that I would need to be going through however none of the key->value pair are always going to be the same. Some of these key names can be spelled different or have numbers on the end of the names so I need to be able to have them dynamic.

Here is an exact example of the JSON I would be cycling through

[
{
"var5":"item-company-1",
"asd2":"item-company-1",
"tie1":"0",
"cxs1":"481.891px",
"xcve2":"130.563px"
},...


I understand if I know the exact name of the key I would do something like..

$someObject = json_decode($someJSON);
print_r($someObject); // Dump all data of the Object
echo $someObject[0]->name; // Access Object data


However I don't know the keys. I assume a for next loop would have to be created to cycle through each object, but I have no clue how to do that in PHP.

Answer

Im assuming your json is always of the below format

$json = '[  
   {  
      "var5":"item-company-1",
      "asd2":"item-company-1",
      "tie1":"0",
      "cxs1":"481.891px",
      "xcve2":"130.563px"
   },
   {  
      "var6":"item-company-2",
      "asd7":"item-company-2",
      "tie8":"0",
      "cxs9":"481.891px",
      "xcve10":"130.563px",
      "extra" : "unknown"
   }
]';

Then you can convert the whole JSON into an array and run a loop

$array = json_decode ($json ,true);

foreach ($array as $item) {
    foreach($item as $key => $value) {
        echo $value;
    }
}
Comments