php - 按观众数量对 PHP 数组进行排序

标签 php arrays json api sorting

我正在开发一个自定义脚本(现在,它是脏的)。基本上它列出了我数据库中的流信息和链接。同时,它从 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>";

最佳答案

使用提供的 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>";
 ?>

关于php - 按观众数量对 PHP 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22720390/

相关文章:

arrays - 在 O(n) 时间内合并具有常量内存的数组的两个排序部分

javascript - 无法使用 JavaScript 从 URL 中获取 JSON

json - Google API的可解码结构

javascript - json 作为 php 变量

php - 访问数据库 : TOP clause and nested queries + PHP Paging

php - 使用 wp_remote_post() 将带有图像的多部分表单数据发布到 iNaturalist REST API

javascript - localStorage仅保存数组的第一个成员

java - 如何接受和输出数组中的 double 和整数?

php - 使用 PHP 在 WSDL 中使用奇怪的附加响应

php - 如何动态访问可变多维数组中的值