How to make iteration over array values to the true conditions?

In General, the written script that reposts from groups Vkontakte schedule(1 record from each group every day). Later noticed that there are always reposts of the groups. Decided to revise the code and this is what I noticed:
Takes a random element in the array (write on the wall) and checked for the conditions. That's right - do a repost.
So as to make these conditions were checked before choose a random element of the array (post). In order to choose the post of an already proven and passing on the condition. Here is my code, which currently bypasses a repost:
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));
}
July 12th 19 at 17:16
1 answer
July 12th 19 at 17:18
Solution
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;



 // Remove items that don't match the condition
 $wall = array_filter($wall, function($entry) {
 return ($entry->post_type == 'post' && $entry->is_pinned !== -1);
});

 // Reindex the array so that the keys go in order
 $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));
}

Find more questions by tags PHPVKontakte