lStoilov
lStoilov

Reputation: 1339

JSON Get the name of dynamically changing key with PHP

I am having trouble getting the name of a dynamic key from a JSON string. I am using PHP

This is a sample of the JSON

{
"_text": "this is a test",
"entities": {
    "dynamic_key": [
        {
            "confidence": 0.99,
            "value": "thi is the answer"
        }
    ]
},
"msg_id": "1234532123"
}

I am using foreach to go trough the json key and get the values

foreach ($json as $obj) {
        $search_term = $obj->_text;
        $msg_id = $obj->msg_id;
    }

But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.

Any ideas on how to approach this?

Followed @Dimi, solution. This is what I ended up with

$data=json_decode($json,true);

foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";

    foreach ($data['entities'] as $keys){
        $conf = $keys[0]['confidence'];
        $answer = $keys[0]['value'];
        echo "conf: $conf, answ: $answer";
    }
}

Upvotes: 1

Views: 1038

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 79004

If you decode the JSON as an array and if the dynamic key is the only key under entities, then:

$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];

Or shorter:

$confidence = current($array['entities'])['confidence'];

You can probably use reset, current and maybe array_pop etc.

Upvotes: 1

Dimi
Dimi

Reputation: 1267

Can you provide a couple more examples? Or try this code and let us know if it breaks

<?php

$json='{
"_text": "this is a test",
"entities": {
    "dynamic_key": [
        {
            "confidence": 0.99,
            "value": "thi is the answer"
        }
    ]
},
"msg_id": "1234532123"
}';


$data=json_decode($json,true);

foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);


}

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57131

Using the data you've shown, there doesn't seem to be an array for the starting JSON.

But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...

$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities )    {
    echo $key.PHP_EOL;
    foreach ( $entities as $entity) {
        echo $entity->confidence.PHP_EOL;
    }
}

Upvotes: 1

Related Questions