E
E
Eugene2019-01-14 15:55:09
PHP
Eugene, 2019-01-14 15:55:09

How to extract city title from json request in PHP script for VK API?

Hello!
I am learning PHP using the VK API as an example. This comes to me:

{
"response": [
{
"id": 3346346,
"first_name": "Имя",
"last_name": "Фамилия",
"sex": 1,
"screen_name": "id43346346",
"bdate": "5.2",
"city": {
"id": 1,
"title": "Москва"
},
"country": {
"id": 1,
"title": "Россия"
},
"photo_max_orig": "https://pp.userapi.com/3453453-O64.jpg?ava=1"
}
]
}

I learned how to save fields such as first name or last name into a variable, but I don’t understand how to save the title of the country field into a declared variable.
Here's how I store user data in variables:
//и извлекаем из ответа его имя 
$first_name = $user_info->response[0]->first_name; 
//и извлекаем из ответа его фамилию 
$last_name = $user_info->response[0]->last_name;
//и извлекаем из ответа его страну 
$country = $user_info->response[0]->country;
//и извлекаем из ответа его город 
$city = $user_info->response[0]->city;

Then I use the variables in the message like this:
//С помощью messages.send отправляем ответное сообщение 
$request_params = array( 
'message' => "Hello, Имя:{$first_name} Фамилия:{$last_name} Страна:{$country} Город:{$city}!", 
'user_id' => $user_id, 
'access_token' => $token, 
'v' => '5.50' 
);

The first and last name are substituted, but the city and country are not.
They write that it is an object, in another place they write that it is an array. Long story short, I'm confused and can't figure it out. Pliz, help.
UPD1: Tried like this, but it doesn't work either:
$country = $user_info->response[0]->country->title;
$city = $user_info->response[0]->city->title;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2019-01-14
@StockholmSyndrome

$country = $user_info->response[0]->country->title;
$city = $user_info->response[0]->city->title;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question