按观看数量对PHP数组进行排序

3
我正在开发一段自定义脚本(目前还比较混乱)。基本上,它会列出存在于我的数据库中的流信息和链接。同时,脚本会从twitch.tv 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>";

可能是按值对多维数组进行排序的重复问题。 - Pitchinnate
1个回答

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>";
 ?>

警告: usort() 函数期望参数2为有效回调函数,但在///***的第19行上却未提供数组或字符串。 - Luigi R.
你的 $json_array 出了点问题。请在这里发布 var_dump($json_array)。 - makallio85
问题在于,你的 $json_array 不是一个数组。如果你解码一个 JSON 字符串,它会变成一个对象。请看我的更新答案。 - makallio85
实际上,问题在于这个流不是数组。 - makallio85

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接