2014-03-28 68 views
3

正在開發自定義腳本(現在,它很髒)。基本上它列出了我的數據庫中的流信息和鏈接。同時,它從twitch.tv API獲取信息。從API中檢索的信息之一是觀衆的數量。如何根據觀衆的數量對列表進行排序,最高優先?我嘗試使用排序功能,但我不知道如何在這種情況下使用它。按觀衆數量排序PHP數組

這是腳本。

// 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

[按值排序多維數組(可能重複http://stackoverflow.com/questions/2699086/sort-multi-按值排列) – Pitchinnate

回答

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

警告:usort()期望參數2是一個有效的回調函數,在第19行的/ ***/***/***中沒有給出數組或字符串 –

+0

有什麼問題你的$ json_array。在這裏發佈var_dump($ json_array) – makallio85

+0

Aaa。錯過觀衆索引..查看更新後的帖子 – makallio85