Twitter API - Same cursor error - php

From REST API of twitter I user get/followers function.
I pasted a code snippet below.
My problem is, modt of the time I get followers' ids successfully. But when a user has more than 5000-6000 followers then my results comes wrong.
When I check from user's profile page, I see that user has 5500 followers, but when I run following code, most of the time 5500 ids come, but sometimes 29994 followers come inside $ids variable. Now I'm logging the results having more then 29k followers. I saw some of the requests returned with 29994 followers, but I couldn't find the answer.
Do I miss something in get ids - cursor approach? Thank you
Edit: After some debugging I logged "$cursor_archieve" parameter and found out this:
* Sometimes next_cursor and previous_cursor comes same:
Array
(
[0] => -1
[1] => 1400573121087317741
[2] => 1400573121087317741
[3] => 1400573121087317741
[4] => 1400573121087317741
[5] => 1400573121087317741
[6] => 1400573121087317741
)
So in this situation, although user has 7100 followers I get only 5000 followers
Sometimes cursors come sequentially same:
Array
(
[0] => -1
[1] => 1404335879106773348
[2] => 1404341060469987526
[3] => 1404338682006540390
[4] => 1404341060469987526
[5] => 1404335879106773348
[6] => 1404338682006540390
)
My code is like this:
public function getIds($user = "someuser"){
$tmhOAuth = new tmhOAuth(array( 'consumer_key' => YOUR_CONSUMER_KEY,
'consumer_secret' => YOUR_CONSUMER_SECRET,
'user_token' => $atoken1, 'user_secret' => $atoken2, ));
$cursor = '-1';
$ids = array();
$cursor_archieve = array();
while(true):
$code=$tmhOAuth->request('GET', $tmhOAuth->url('1/followers/ids'),
array('screen_name' => $user, 'cursor' => $cursor));
if ($code == 200) {
$responseData = json_decode($tmhOAuth->response['response'],true);
$ids = array_merge($ids, $responseData['ids']);
$cursor = $responseData['next_cursor_str'];
$cursor_archieve[] = $cursor;
} else {
return 0;
}
if ( $cursor == '0' || count($ids) >= 29000 ) {
break;
}
endwhile;
return $ids;
}
edit2: Should I make "array_unique" to delete duplicate ids, or doesn't use next cursor if previous_cursor=next cursor or any other option?
In every case user has 5500-6500 followers. So If I take only one cursor, I only can get first 5000 followers.

The reason was a programatic error in my codes. I fixed it after a week's debug session

Related

Compare a value in array in php - if not exist then add that to json array

I know it's very simple but I'm unable to resolve this. Please look into this.
I have a table called notification_updates and it's array is like this:
Array
(
[0] => common\models\NotificationUpdates Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[id] => 1
[title] => This is the notification to inform you about this.
[status] => 1
[created_at] => 2017-11-20 08:29:21
)
)
[1] => common\models\NotificationUpdates Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[id] => 2
[title] => This is the notification to inform you about this cricket match
[status] => 1
[created_at] => 2017-11-20 06:24:09
)
)
[2] => common\models\NotificationUpdates Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[id] => 3
[title] => Inform you about this cricket match
[status] => 1
[created_at] => 2017-11-21 11:40:31
)
)
)
Now I have 1 more table where primary_key (id) of first table is foriegn called notification_id in table deleted_nofitication.
This table also has array like this:
Array
(
[0] => common\models\DeletedNofitication Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[notification_id] => 1
)
)
[1] => common\models\DeletedNofitication Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[notification_id] => 2
)
)
)
Now I have to check weather notification_updates table have this value against that user_id. If it's there then it should not that notification should not be displayed under JSON.
I have Done like this in PHP (YII2) - not doing compare in this please check
$notifications = NotificationUpdates::find()->where([])->all();
$outt = [];
foreach($notifications as $notification) {
$deleted_notification = DeletedNofitication::find()
->select('notification_id')
->where(['user_id'=>$user_id])
->all();
$outt[] = [
'id' => $notification->id,
'notification_title' => $notification->title
];
}
$out = [
'notification'=> $outt,
'success' => true,
'message' => 'All Notification Updates'
];
EDIT:
Alright, now that I get what you're trying to do, I might be able to help. I'm not comfortable with YII2 (i.e. I've never used it), but your code may look something like this. The bottomline is that I want the SQL to only return the relevant records, so that we don't have to do that logic with our php:
<?php
// We're trying to select all notifications except the ones that have already been shown.
// Following query uses subquery, join would be better performancewise.
// $notificationsSQL = "SELECT id,title FROM NotificationUpdates WHERE id NOT in (SELECT id FROM DeletedNotifications WHERE user_id = $user_id)";
$notificationsAlreadyShown = DeletedNofitication::find()->where(['user_id' => $user_id]);
$notifications = NotificationUpdates::find()->where(['not in', 'id', $notificationsAlreadyShown]);
if ($notifications->count() === 0){ //Or whatever method you use to count the results.
return; // Or whatever you need to do to handle this case.
}
$outt = [];
foreach ($notifications->all() as $notification) {
$outt[] = [
'id' => $notification->id,
'notification_title' => $notification->title
];
}
$out = [
'notification' => $outt,
'success' => true,
'message' => 'All Notification Updates'
];
P.s I don't see a column user_id on your deletednotifications, might be something to check.
OLD ANSWER:
Sorry, you're question isn't exactly clear to me. I.e. I don't get what you're trying to do. Is it only show the notifications that haven't been deleted?
The first thing that catches my eye, is that you're have a column user_id in the where-clause of your 2nd query, but I don't see it in the table structure. I'm not too familiar with YII2, but are you perhaps trying to do something along the lines of:
<?php
$notifications = NotificationUpdates::find()->where([])->all();
$outt = [];
foreach ($notifications as $notification) {
$deleted_notification = DeletedNofitication::find()
->select('notification_id')
->where(['notification_id' => $notification->id])
->all();
// If the notification has been deleted, skip to next iteration.
if (count($deleted_notification) > 0){
continue;
}
$outt[] = [
'id' => $notification->id,
'notification_title' => $notification->title
];
}
$out = [
'notification' => $outt,
'success' => true,
'message' => 'All Notification Updates'
];
Although if that's what you're trying to do, you should probably go back to your query builder and only select the notifications that aren't deleted. Or even better, use YII2s softdeletes (if it has that).
This query does this everything which i needed..
$sql = "select * from notification_updates where NOT EXISTS
(select * from deleted_nofitication where notification_id = notification_updates.id AND user_id = ".$user_id." )" ;
$command = Yii::$app->db->createCommand($sql);
$notifications = $command->queryAll();
And taking the value from $notifications and add that to json.

Saving Mikrotik Simple Queue Statistic PHP API

I want to save the statistics of the Mikrotik /simple queue using the PHP API. I have been able to pull the data but seems my implementation on the PHP side is a problem. The following is the code and the resulting array object.
foreach ($util->setMenu('/queue simple')->getAll() as $queueEntry) {
// $lasArray = $queueEntry;
print_r($queueEntry);
}
Excerpt for Result since its returning for all users in the office, I have choosen just to display for one user. Take it that PEAR2\Net\RouterOS\Response Object is retuned for all users, i.e all in this case over 50 users. I would like to save this data to database but only the relevant ones like [.id], [name], [target], [limit-at], [max-limit] and [bytes], any assistance here would be highly regarded.
PEAR2\Net\RouterOS\Response Object
(
[unrecognizedWords:protected] => Array
(
)
[_type:PEAR2\Net\RouterOS\Response:private] => !re
[attributes:protected] => Array
(
[.id] => *12
[name] => GikundaPhone
[target] => 192.168.1.108/32
[parent] => none
[packet-marks] =>
[priority] => 8/8
[queue] => default-small/default-small
[limit-at] => 128000/384000
[max-limit] => 384000/384000
[burst-limit] => 0/0
[burst-threshold] => 0/0
[burst-time] => 0s/0s
[bucket-size] => 0.1/0.1
[bytes] => 16515474/129310087
[total-bytes] => 0
[packets] => 127812/133712
[total-packets] => 0
[dropped] => 76/8667
[total-dropped] => 0
[rate] => 0/0
[total-rate] => 0
[packet-rate] => 0/0
[total-packet-rate] => 0
[queued-packets] => 0/0
[total-queued-packets] => 0
[queued-bytes] => 0/0
[total-queued-bytes] => 0
[invalid] => false
[dynamic] => false
[disabled] => false
)
[_tag:PEAR2\Net\RouterOS\Message:private] =>
)
Have found and answer to my own question. This is what I have done. The
foreach ($util->setMenu('/queue simple')->getAll() as $queueEntry) {
// $lasArray = $queueEntry;
print_r($queueEntry);
}
provided alot of information thats unnecessary, so I have found about the routeros_api.class.php downloadable from here and followed but modified information from here. Then just used
$address = 'IPV4_Address_of_router';
$user = 'username_of_router';
$pass = 'password_of_router';
require('routeros_api.class.php');
$API = new routeros_api();
$API->debug = false;
// router credentials and after including the routeros_api.cass.php
if ($API->connect($address, $user, $pass)) {
$results = $API->comm("/queue/simple/print");
foreach ($results as $row) {
$clientName = $row['name'];
$clientIP = $row['target'];
$clientMaxDown = $row['limit-at'];
$clientMaxUp = $row['max-limit'];
$clientDownloads = $row['bytes'];
}
}
Only thing remaining was to save to database which is simple. Maybe someone may get helped someday by this.

get instagram user id using php foreach in wordpress

I created wordpress shortcode to get user ID by search,
I using foreach() but result not working!
I want foreach because i will make shortocde to get latest instagram images,
Resource:
http://instagram.com/developer/endpoints/users/
http://codex.wordpress.org/Function_Reference/wp_remote_get
http://codex.wordpress.org/Function_Reference/wp_remote_retrieve_body
This is my code:
function insta_id($atts, $content = null){
$my_access_token = "MY ACCESS TOKEN IS HERE";
$get_id = wp_remote_get("https://api.instagram.com/v1/users/search?q=youtube&access_token=$my_access_token&count=2");
$retrieve_id = wp_remote_retrieve_body( $get_id );
$result = json_decode($retrieve_id, true);
foreach ( $result as $user_id ) { // loop start
print_r($user_id); // this working but display all array
echo $user_id->id; // not working!
}
}
add_shortcode("insta_id", "insta_id");
print_r($user_id); display this:
Array ( [0] => Array ( [username] => youtube [bio] => Behind the scenes with stars from your favorite YouTube channels. [website] => [profile_picture] => http://photos-b.ak.instagram.com/hphotos-ak-xaf1/10691785_700124036737985_752862120_a.jpg [full_name] => [id] => 1337343 ) [1] => Array ( [username] => youtubewtfff [bio] => ғυnniest moments on yoυтυвe 😂 Kik: Youtubewtf Email : tysroark#hotmail.com Want a shoutout? Tag #Youtubewtf [website] => [profile_picture] => http://images.ak.instagram.com/profiles/profile_489772119_75sq_1391400797.jpg [full_name] =>
You may be retrieving the wrong key from the response. Double check the instagram User ID with https://www.thekeygram.com/find-instagram-user-id/
It should be: $user_id['id']

How to access more than 10 item's detail in Amazon api using php?

I am working with amazon api and have used code from online sources http://www.codediesel.com/php/accessing-amazon-product-advertising-api-in-php/.
I would like to get more than 10 product's detail when I make a search query using amazon api. I am aware about the amazon api policy of getting 10 data per call but is it possible to get more data by creating loop or something?
When I make a request I have assigned following parameteres
$parameters = array("Operation" => "ItemSearch",
"SearchIndex" => "Electronics",
"ResponseGroup" => "Images,ItemAttributes,EditorialReview,Offers ",
"ItemPage"=>"10",
"Keywords" => $search );
So even though I have asked for 10 pages of result, I am unsure of how to display data from every page (1 to 10 ) so in total I get 100 items when I make a query. I get following response when I try to make run the code:
SimpleXMLElement Object (
[Request] => SimpleXMLElement Object (
[IsValid] => True
[ItemSearchRequest] => SimpleXMLElement Object (
[ItemPage] => 10
[Keywords] => laptop
[ResponseGroup] => Array (
[0] => Images
[1] => ItemAttributes
[2] => EditorialReview
[3] => Offers
)
[SearchIndex] => Electronics
)
)
[TotalResults] => 3383691
[TotalPages] => 338370
[MoreSearchResultsUrl] => http://www.amazon.co.uk/gp/redirect.html?camp=2025&creative=12734&location=http%3A%2F%2Fwww.amazon.co.uk%2Fgp%2Fsearch%3Fkeywords%3Dlaptop%26url%3Dsearch-.................(and on)
)
Yes, you would need to loop through 10 times and appends an array or object. The AWS documentation says that ItemPage is actually the page of results, so you would just need to page through it 10 times to get your 100 results.
AWS Documentation on ItemPage:
http://docs.aws.amazon.com/AWSECommerceService/latest/DG/PagingThroughResults.html
$obj = new AmazonProductAPI();
$results = array();
for ($i=1;$i<=10;$i++) {
$parameters = array("Operation" => "ItemSearch",
"SearchIndex" => "Electronics",
"ResponseGroup" => "Images,ItemAttributes,EditorialReview,Offers ",
"ItemPage"=>$i,
"Keywords" => $search);
$results[] = $obj->searchProducts($parameters);
}
foreach ($results as $r) {
//do your stuff
}
We can use manufacturer parameter along with BrowseNode to retrieve more than 100 products in a specific category.

pagination within the facebook API (photos)

I'm currently developing a facebook app that needs access to a users photos. It needs to loop through all of the users active photos however I'm having some trouble with the pagination aspect of the feed. I get results from the API like
stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[id] => 10151796309135076
[from] => stdClass Object
(
[name] => Daniel Benzie
[id] => 762525075
)
)
)
)
obviosuly the above is an excerpt and then down the bottom there is a section for next and previous pages.
[previous] => https://graph.facebook.com/762525075/photos?access_token=xxxxxxx&limit=25&since=1338985293&__previous=1
[next] => https://graph.facebook.com/762525075/photos?access_token=xxxxx&limit=25&until=1332002972
this is always set- does anyone know the best way to loop through the photos in this case? thanks in advance (:
Keep calling the next url until there is no more data
while ($some_photos['data'])
{
$all_photos = array_merge( $all_photos, $some_photos['data'] );
$paging = $some_photos['paging'];
$next = $paging['next'];
$query = parse_url($next, PHP_URL_QUERY);
parse_str($query, $par);
$some_photos = $facebook->api(
$user_id."/photos", 'GET', array(
'limit' => $par['limit'],
'until' => $par['until'] ));
}

Categories