There was a parser script that uploaded posts from a third-party site. Everything worked until I moved to another hosting. (PHP version is the same everywhere 7.0.) The parser is working but under the half of the posts this message pops up

Warning: Invalid argument for foreach () in /var/www/u0000000/data/www/test.ru/fars.php on line 83

And the first_name field is left blank. Although the information is on a third-party site. Tell me what could be the problem?

Part of the code with 80 lines:

 function user($id){ $url = 'https://api.vk.com/method/users.get?user_ids='.$id.'&version=5.73&fields=city,photo_100&access_token=asdfasdf'; $result = file_get_contents ($url); $b = json_decode($result, true); $result = file_get_contents ($url); $b = json_decode($result, true); // Перебирает массив засовывает в переменную value. foreach($b['response'] as $value) : endforeach; $first_name = $value['first_name']; $avatar = $value['photo_100']; // Достает город. if ($value['city'] == 113) { $city = 'Москва'; }elseif ($value['city'] == 4433) { $city = 'СПБ'; }elseif ($value['city'] == 889) { $city = 'Воронеж'; } else { $city = 'Город не определен'; } //возвращает ответ из переменной $b return compact('first_name','city','avatar'); } 
  • Are you an array of iterating over something in a loop to get to the last element? $value = end($b['response']) not easier? PS: look at what you return by reference, make sure that there is a valid json and it has a response field, which is an array. and replace the if-elseif construct with switch or an array of values. - teran
  • You really want to ask us here what lies in your $ b ['response'] variable? - Ipatiev
  • A little corrected the description. I iterate over the array in the user function. - Dmitriy
  • @teran response is returned full. Half of the posts at the output are full. The other part without the name "first_name" with this error. - Dmitriy
  • in your error text it is written in black and white that the array is not passed in foreach . so no matter what's in first_name . error before - teran

1 answer 1

Not much redid your code, everything works on the local server

 function user($id){ $id = ; $token = ''; $v = '5.80'; $request = [ 'user_ids' => $id, 'fields' => 'city,photo_100', 'access_token' => $token, 'v' => $v ]; $rez = json_decode(file_get_contents('https://api.vk.com/method/users.get?'.http_build_query($request))); if($rez->response) { foreach ($rez->response as $res) { $first_name = ($res->first_name) ?: ''; $avatar = ($res->photo_100) ?: ''; $city = ($res->city->id) ?: ''; } } return compact('first_name','city','avatar'); }