N
N
Niko2017-08-21 22:42:04
PHP
Niko, 2017-08-21 22:42:04

How to check for an empty array in the VK API?

Good day. I get statistics for the VKontakte group, I collect statistics through the stats.get method , everything works fine, everything works. But there is one problem. There are groups in which there are no statistics, i.e. there are no views and nowhere to get numbers from (it gives {"response":[]} ). And it turns out that he takes statistics from the previous group. For example: Groups go in order.
Group 1 - Views : 42 ,
Group 2 - Views : 42 ,
but there are no views in Group 2 , there is no place to take values ​​from {"response":[]} gives, but it takes views from the previous group. How do I check or how can I solve the problem?

$url_for_stats = "https://api.vk.com/method/stats.get?" . http_build_query($request_params_for_stats);	
$result_stats = file_get_contents($url_for_stats);
$decode_stats = json_decode($result_stats);
foreach ($decode_stats->response as $stats_result) 
$views = $stats_result->views;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Serezha, 2017-08-22
@NeroKore

But the get.stats method allows you to get data only by 1 group id. Where did the forich come from, lol?
Here, for understanding, I dashed off a small script, without error checks from VK (!):

<?php
/**
 * Created by PhpStorm.
 * User: Ahen
 * Date: 22.08.2017
 * Time: 7:10
 */

// Токен пользователя с разрешением stats
$access_token = '';

// Массив с id групп
$groups = [1, 2, 3];


/**
 * @param $params array - Массив параметров запроса, содержит group_id, date_from, date_to.
 * @param $access_token - Строка, содержащая токен пользователя.
 * @return array - Массив, содержащий group_id и views
 */
function statsGet($params, $access_token)
{
    //Запрос, обернутый в json_decode
    $request = json_decode(file_get_contents("https://api.vk.com/method/stats.get" .
        "?group_id=" . $params["group_id"] .
        "&date_from=" . $params["date_from"] .
        "&date_to=" . $params["date_to"] .
        "&access_token=" . $access_token .
        "&v=5.68"));

    // Если $request->response[0]->views существует, то присваиваем его значение к $views.
    // Иначе присваиваем $views значение 0.
    if ($request->response[0]->views) {
        $views = $request->response[0]->views;
    } else {
        $views = 0;
    }

    // Возвращаем массив
    return ["group_id" => $params["group_id"], "views" => $views];
}

// Объявляем $result как массив
$result = array();

// Обходим форичем массив id групп
foreach ($groups as $group) {
    // Пушим результат из функции в массив
    $result[] = statsGet(
        ["group_id" => $group,
        "date_from" => "2013-08-08",
        "date_to" => "2013-09-08"], 
        $access_token);
    // Слип на 1/3 секунды, чтобы не ловить ошибок вк
    usleep(334000);
}

// Простой вывод для теста
foreach ($result as $item) {
    echo "В группе с id: {$item['group_id']} просмотров: {$item['views']} <br/>";
}

U
Uncle Seryozha, 2017-08-22
@Protos

Um, I don’t rummage in php, but before getting the value, I have a simple function to search for the error text in the received string, before assigning a value to the decode_stats[i] value, i.e. Something like checking: if(... contains("{"response":[]}") ) {error}
If ... contains("error") {error}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question