Reputation: 1591
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.
Upvotes: 2
Views: 2067
Reputation: 1591
I marked the answer because he technically answered my question.
I also found this solution hopefully it might help someone in the future as a great alternative to the above. This will actually go over a multi-level array to get out all the values.
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Upvotes: 0
Reputation: 3360
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;
}
}
Upvotes: 2