-1

How can I access this variable in php ?

result->message->from->id

I decoded returned json with json_decode() and I want to get value Through the above method

{
    "ok": true,
    "result": [
        {
            "update_id": 176446579,
            "message": {
                "message_id": 7,
                "from": {
                    "id": 468822221,
                    "is_bot": false,
                    "first_name": "M.GH",
                    "last_name": "2003",
                    "username": "moji_2003",
                    "language_code": "fa"
                },
                "chat": {
                    "id": 468822221,
                    "first_name": "M.GH",
                    "last_name": "2003",
                    "username": "moji_2003",
                    "type": "private"
                },
                "date": 1550384619,
                "text": "salam"
            }
        }
    ]
}
  • it's all already clearly mentioned in [PHP's manual](http://php.net/manual/en/function.json-decode.php). – yqlim Feb 18 '19 at 09:34

2 Answers2

1

$result is an array, so you need to first access the first element in the array:

$json = json_decode('JSON_STRING');

$id = $json->result[0]->message->form->id;
BenM
  • 52,573
  • 26
  • 113
  • 168
  • 1
    According to [PHP's `json_decode` manual](http://php.net/manual/en/function.json-decode.php), the function returns a `stdClass` instead of an array if the function's 2nd argument is not set to `true`. Nevertheless, it can still be used like an array. – yqlim Feb 18 '19 at 09:35
  • An error occurs : Notice: Trying to get property 'result' of non-object in C:\xampp\htdocs\Gptec-telebot\classes\robot.php on line 23 Notice: Trying to get property 'message' of non-object in C:\xampp\htdocs\Gptec-telebot\classes\robot.php on line 23 Notice: Trying to get property 'form' of non-object in C:\xampp\htdocs\Gptec-telebot\classes\robot.php on line 23 Notice: Trying to get property 'id' of non-object in C:\xampp\htdocs\Gptec-telebot\classes\robot.php on line 23 – Sahar Zakeri Feb 18 '19 at 09:37
  • tnx probleme resolved – Sahar Zakeri Feb 18 '19 at 09:44
  • @YongQuan while true, if the generated object contains an array, it will still contain an array when decoded. Passing `true` to the second argument would mean we have to use: `$json['result'][0]['message']['form']['id']`. – BenM Feb 18 '19 at 18:59
1

Yes, you can access it this way:

 $data = json_decode($yourJsonString);
 echo $data->result[0]->message->from->id;
Andrii Filenko
  • 954
  • 7
  • 17