Home > database >  Trying to access specific values from json response in PHP
Trying to access specific values from json response in PHP

Time:03-18

I have a JSON response that is variable and I am trying to access some specific value from JSON, the problem is in the variable name is also dynamic so we cant access its name directly it returns an error because the response fields name is also dynamic.

Here is my response:

{"ggru":195,"_grant_1647561070":"ya88op110","success":true}

What exactly I want from this response is that I want to access _grant_1647561070 value ya88op110 but this _grant_1647561070 numbers will be changed every time when session is refreshed also I want that this number 1647561070 in a variable.

So response should like this: variable a= ya88op110; variable b= 1647561070;

Anyone can help me?

CodePudding user response:

You didn't say this, but I have to assume that the _grant_ is a constant in the json string. If that is true you could do:

<?php

$json  = '{"ggru":195,"_grant_1647561070":"ya88op110","success":true}';
$array = json_decode($json);
foreach ($array as $key => $value) {
    if (substr($key, 0, 7) == '_grant_') {
        $a = $value;
        $b = substr($key, 7);
        break;
    }
}
echo "a = $a\n<br>\nb = $b";

This returns:

a = ya88op110
<br>
b = 1647561070

The code is quite self-explanatory: Search for the key that starts with _grant_ and extract the values.

  • Related