Answer the question
In order to leave comments, you need to log in
How to access a property of an object without knowing its name?
Hello, such json comes from the database. The problem is that the names phone_lg, phone_samsung will always be different - how to access them in a loop without knowing them.
[{
"id_predmet": "24",
"json_param": {
"phone_lg": {
"price": "200",
"old_price": "300"
}
}
}, {
"id_predmet": "25",
"json_param": {
"phone_samsung": {
"price": "400",
"old_price": "500"
}
}
}]
Answer the question
In order to leave comments, you need to log in
For example, you can collect unknown keys in a separate array and then take these values from it:
$predmet = json_decode($json, true);
$keys = array_map(function ($n) {
return array_keys($n['json_param'])[0];
}, $predmet);
$i = 0;
foreach ($predmet as $inv_val) {
echo $inv_val['json_param'][$keys[$i]]['price'];
$i++;
}
You can do this:
foreach($predmet as $inv_field => $inv_val) {
$price = current((array) $inv_val->json_param)->price;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question