1
votes

I'm using the twitter API via CodeBird PHP to display tweets using Ajax on a site. I'm having trouble preventing duplicates after the first call since max_id shows tweets after BUT INCLUDING the max_id.

Seems silly why they'd do it this way, to me, but I also can't seem to find anyone else asking the same question. I though this would be something that a lot of people come across. Which leads me to think I'm not doing something correctly.

    // Prepare Args
    $tw_args = array(
        'count' => 5,
        'trim_user' => true
    );

    // If we havea last id, set it
    if (isset($last_id)) {
        $tw_args['max_id'] = $last_id;
    }

    // new tweet arr
    $tweets = array();

    // get raw tweets
    $raw_tweets = (array) $cb->statuses_userTimeline($tw_args);

    // loop through tweets
    for ($i = 0; $i < count($raw_tweets); $i++) { 

        // Add just the ID and text to our new tweets array
        $tmp = array(
            'id' => $raw_tweets[$i]->id_str,
            'text' => $raw_tweets[$i]->text
        );

        array_push($tweets, $tmp);
    }


    // return tweets array
    return $tweets;

How do you prevent the twitter API returning the tweet with the same id as max_id?

2

2 Answers

1
votes

If I understood well what you're trying to do, it seems that the max_id tweet is included in the $raw_tweets array?

If so, simply add a condition in your loop to not add the tweet with max_id as id to the $tweets array :

    // ...

    for ($i = 0; $i < count($raw_tweets); $i++) {

        // Check if the current tweet's id match max_id
        if($raw_tweets[$i]->id_str == max_id)
            continue;

        // Add just the ID and text to our new tweets array
        $tmp = array(
            'id' => $raw_tweets[$i]->id_str,
            'text' => $raw_tweets[$i]->text
        );

        array_push($tweets, $tmp);
    }

    // ...
1
votes

If your platform is capable of working with 64-bit integers, simply subtract 1 from whatever value you have determined to be the max_id. According to the API documentation here, "It does not matter if this adjusted max_id is a valid Tweet ID, or if it corresponds with a Tweet posted by a different user - the value is just used to decide which Tweets to filter." This will prevent receiving any duplicates.

However, if you cannot process 64-bit integers, the documentation says to skip this step, so I would assume there is no simpler workaround than the one offered by ZeusInTexas.