I'm having problems passing the results of a friends/ids
request to a users/lookup
request while using Abraham's Twitter OAuth (https://twitteroauth.com/) PHP library to access the Twitter REST API.
After authenticating, I get an account's friends list as user ids:
$content = $connection->get("followers/ids", ["screen_name" => $input]);
Then I'm creating a comma separated list:
foreach ($content as $user) {
$userlist = implode(', ', $user);
And then I'm passing this to a users/lookup request:
$output = $connection->post("users/lookup", ["user_id" => $userlist]);
This gives a code 17 error which I understand to mean no such account was identified by Twitter. Outputting the imploded $userlist
shows this step is working ok.
If I define $userlist
myself then the subsequent call to users/lookup
works fine. For example:
$userlist = "820310862045052930, 806614673474912256, 745020013837434880, 789205729123065860, 717272899741204480, 2523773164, 763810846929719296, 817061186705457152, 806495626670186496, 1935657786, 813858305282109442, 224295002, 24016369, 719472791200739328, 3292608016, 544394440, 338499233, 704776216, 1080910670, 2162932007, 15700673, 2212757984, 375238808, 2949937593, 244523746, 145021177, 4195801821, 799570638847561728"
I've tried converting the results of the first request (friends/ids) to array:
$contentarray = json_decode(json_encode($content), True);
but this makes no difference. I've also tried passing the list of ids as an array (and defining the $userlist as such in the request). Wrapping $userlist
in quotes doesn't work either and it makes no difference if I use GET or POST. Similarly, creating another array of just user_ids (excluding the cursors) and creating a comma separated list from this does not make a difference.
Twitter OAuth is usually so simple and intuitive to use but I've spent hours on this and am getting nowhere. Can anyone help out with where I'm going wrong?
So it turns out the problem was with my foreach
loop. Hat tip to hobbes3 for this answer.
After authenticating:
// get the user's followers
$content = $connection->get("followers/ids", ["screen_name" => $input]);
// replace stdclass object with array
$content_as_array = json_decode(json_encode($content), True);
//create new array with foreach
$content_as_new_array = array();
foreach($content_as_array as $user) {
foreach($user as $newuser) {
array_push($content_as_new_array, $newuser);
}
}
// implode this new array
$userlist = implode(", ", $content_as_new_array);
// and pass this new array to API
$output = $connection->post("users/lookup", ["user_id" => $userlist]);