我正在开发一个自定义脚本(现在,它很脏)。基本上它列出了我的数据库中的流信息和链接。同时,它从twitch.tv API获取信息。从API检索的信息之一是查看者的数量。如何按查看者的数量对列表进行排序,先排名最高?我尝试使用sort函数,但在这种情况下我不知道如何使用它。
这是脚本。
// 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>";
答案 0 :(得分:0)
使用提供的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>";
?>