V
V
verest142019-07-29 18:24:32
PHP
verest14, 2019-07-29 18:24:32

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"
    }
  }
}]

$predmet = json_decode(JSON_WHAT_ABOVE); //take data from the database
foreach($predmet as $inv_field => $inv_val) {
echo $inv_val->json_param->phone_samsung->price;
}
If output directly ($inv_val->json_param->phone_samsung->price) - everything works. But I don't know the property names phone_lg, phone_samsung, etc. How to display data from an object if the names of their properties are not known?
I put a second loop inside foreach - the name displays and I can use it,
foreach($inv_val->json_param as $inv_field2 => $inv_val2) {
echo $inv_field2;
}
but there should be an easier way like: $inv_val->json_param->unknown->price. Tell me please

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DanKud, 2019-07-29
@DanKud

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++;
}

D
Dmitry Koshelenko, 2019-07-29
@GomelHawk

You can do this:

foreach($predmet as $inv_field => $inv_val) {
    $price = current((array) $inv_val->json_param)->price;
}

But it's really a crutch. At least it would be more correct to unify the keys and store the type of phone in another field instead of the key.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question