P
P
Pavel Chuev2016-04-28 17:17:02
PHP
Pavel Chuev, 2016-04-28 17:17:02

How to iterate through array values ​​until the correct condition?

In general, I wrote a script that performs reposts from VKontakte groups on a schedule (1 entry from each group every day). Later I noticed that reposts from groups are not always performed. I decided to revise the code and noticed this:
A random element of the array (a record from the wall) is taken and checked for conditions. That's right - we repost.
So here's how to make sure that these conditions are checked before a random element of the array (post) is selected. In order to immediately select a post from those already checked and passing by condition. Here is my code that currently skips reposts:

while($row = $qwe->fetch()) {
  $wall = file_get_contents("https://api.vk.com/method/wall.get?v=5.4&filter=owner&count=1000&owner_id=-".$row['id']);
  $wall = json_decode($wall);
  $wall = $wall->response->items;
  $i = mt_rand(1, count($wall));
  $x = $wall[$i]->post_type;
  $z = $wall[$i]->is_pinned;
  if($x == 'post')
  {
    if($z !== 1)
    {
      $repost = file_get_contents("https://api.vk.com/method/wall.repost?v=5.4&object=wall-".$row['id']."_".$wall[$i]->id."&group_id=".$gid."&access_token=".$token);
      $repost = json_decode($repost);
    }
  }
  sleep(mt_rand(25, 45));
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2016-04-28
@AllDecay

while($row = $qwe->fetch()) {
    $wall = file_get_contents("https://api.vk.com/method/wall.get?v=5.4&filter=owner&count=1000&owner_id=-".$row['id']);
    $wall = json_decode($wall);
    $wall = $wall->response->items;



    // Удаление элементов, которые не подходят под условие
    $wall = array_filter($wall, function($entry) {
        return ($entry->post_type == 'post' && $entry->is_pinned !== -1);
    });

    // Переиндексация массива, чтобы ключи шли по порядку
    $wall = array_values($wall);



    $i = mt_rand(1, count($wall));
    $repost = file_get_contents("https://api.vk.com/method/wall.repost?v=5.4&object=wall-".$row['id']."_".$wall[$i]->id."&group_id=".$gid."&access_token=".$token);
    $repost = json_decode($repost);

    sleep(mt_rand(25, 45));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question