【问题标题】:Catch Tweets with JSON and sort by likes?用 JSON 捕捉推文并按喜欢排序?
【发布时间】:2018-06-10 05:43:00
【问题描述】:

我目前正在运行一个 wordpress 后端,并希望在我的网站上显示一些基于 hastags 的推文。对于一般的API请求和数据库存储,我使用这个函数:

private function parseRequest($json) {
    $tmp = $json;
    $result = array();

    if (isset($json['statuses'])) {
        $tmp = $json['statuses'];
    }
    if (isset($tmp) && is_array($tmp)){
        foreach ($tmp as $t) {
            $this->image = null;
            $this->media = null;
            $tc = new \stdClass();
            $tc->feed_id = $this->id();
            $tc->id = $t['id_str'];
            $tc->type = $this->getType();
            $tc->nickname = '@'.$t['user']['screen_name'];
            $tc->screenname = (string)$t['user']['name'];
            $tc->userpic = str_replace('.jpg', '_200x200.jpg', str_replace('_normal', '', (string)$t['user']['profile_image_url']));
            $tc->system_timestamp = strtotime($t['created_at']);
            $tc->text = $this->getText($t);
            $tc->userlink = 'https://twitter.com/'.$t['user']['screen_name'];
            $tc->permalink = $tc->userlink . '/status/' . $tc->id;
            $tc->media = $this->getMedia($t);
            @$tc->additional = array('shares' => (string)$t['retweet_count'], 'likes' => (string)$t['favorite_count'], 'comments' => (string)$t['reply_count']);
            if ($this->isSuitablePost($tc)) $result[$tc->id] = $tc;
        }
    }
    return $result;
}

现在我正在寻找一个函数,它将“附加数组”中的所有变量一起计算,例如,shares + likes + cmets 并根据结果数字对所有帖子进行排序。 我正在使用标准的 wordpress sql 数据库。我找不到解决方案,或者我只是盲目的。

感谢您的问候

【问题讨论】:

    标签: php json wordpress twitter


    【解决方案1】:

    您可以使用简单的usort 函数:

    usort($tc, function($a, $b) {
    
        $a_sum = array_sum($a->additional);
        $b_sum = array_sum($b->additional);
    
        if ($a_sum == $b_sum) {
            return 0;
        }
    
        return ($a_sum < $b_sum) ? -1 : 1;
    });
    

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多