【问题标题】:Sort PHP array by amount of viewers按观众数量对 PHP 数组进行排序
【发布时间】:2014-05-08 08:39:57
【问题描述】:

我正在开发一个自定义脚本(现在,它很脏)。基本上它列出了我数据库中的流信息和链接。同时,它从 twitch.tv API 获取信息。从 API 中检索到的信息之一是观看者的数量。如何按观众数量对列表进行排序,最高优先?我尝试使用排序功能,但我不知道在这种情况下如何使用它。

这是脚本。

// developed by Luigi Robles
$con = mysqli_connect("localhost", "****", "****", '****');
$result = mysqli_query($con,"SELECT * FROM streams");
echo "<table border='1'>
<tr>
<th>Stream name</th>
<th>status</th>
<th>game</th>
<th>viewers</th>
</tr>";
while($row = mysqli_fetch_array($result))
 {
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($row['channel']).'?client_id='.$clientId), true);

if ($json_array['stream'] != NULL) {
  echo "<tr>";
  echo "<td>" . $json_array['stream']['channel']['display_name'] . "</td>";
  echo "<td>" . $json_array['stream']['channel']['status'] . "</td>";
  echo "<td>" . $json_array['stream']['channel']['game'] . "</td>";
  echo "<td>" . $json_array['stream']['viewers'] . "</td>";
  echo "</tr>";
  }
  }

 echo "</table>";

【问题讨论】:

标签: php arrays json api sorting


【解决方案1】:

使用提供的 json 数据进行测试并正常工作:

<?php
    $con = mysqli_connect("localhost", "****", "****", '****');
    $result = mysqli_query($con,"SELECT * FROM streams");

    echo "<table border='1'>";
    echo "<tr>";
    echo "<th>Stream name</th>";
    echo "<th>status</th>";
    echo "<th>game</th>";
    echo "<th>viewers</th>";
    echo "</tr>";

    $data = array();
    while($row = mysqli_fetch_array($result)) {
        $json = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($row['channel']).'?client_id='.$clientId), true);
        if(!is_null($json->stream))
            $data[] = array(
                'display_name' => $json->stream->channel->display_name,
                'status' => $json->stream->channel->status,
                'game' => $json->stream->channel->game,
                'viewers' => $json->stream->viewers);
    }
    usort($data, function($a,$b) {return $a['viewers'] < $b['viewers'];});
    foreach($data as $item) {
        echo "<tr>";
        echo "<td>{$item['display_name']}</td>";
        echo "<td>{$item['status']}</td>";
        echo "<td>{$item['game']}</td>";
        echo "<td>{$item['viewers']}</td>";
        echo "</tr>";
    }
    echo "</table>";
 ?>

【讨论】:

  • 警告:usort() 期望参数 2 是一个有效的回调,在第 19 行的 /***/***/*** 中没有给出数组或字符串
  • 你的 $json_array 有问题。在这里发布 var_dump($json_array)
  • 好吧,这里的问题是,你的 $json_array 不是数组。如果你解码一个 json 字符串,它将变成一个对象。请参阅我的更新答案。
  • 其实这里的问题是,那个流不是数组。
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
相关资源
最近更新 更多