3

Im developing a custom script (right now, it is dirty). Basically it lists the stream info and links that are in my database. At the same time, it gets info from the twitch.tv API. And one of the info retrieved from the API is the amount of viewers. How do I sort the list by the amount of viewers, highest first? I tried using the sort function but I don't know how to use it in this case.

Here's the script.

// 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>";
Luigi R.
  • 229
  • 4
  • 20
  • possible duplicate of [Sort Multi-dimensional Array by Value](http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value) – Pitchinnate Mar 28 '14 at 18:30

1 Answers1

0

Tested with provided json data and working:

<?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>";
 ?>
makallio85
  • 1,366
  • 2
  • 14
  • 29