2016-08-11 67 views
0

最近我一直對PHP很好奇,並且正在開發一個測試主題。我想從網絡遊戲中獲得公民的人數,並按軍銜排序。使用php訂購json api

這裏是API的鏈接:https://www.erevollution.com/en/api/citizenship/1

這裏是我到目前爲止的代碼。

<form action="index.php" method="post"> 
    <input type="text" name="id"><br> 
    <input type="submit"> 
</form> 
<?php 
$okey= $_POST["id"];; 
$jsonurl="https://www.erevollution.com/en/api/citizenship/".$okey; 
$json = file_get_contents($jsonurl,0,null,null); 
$json_output = json_decode($json); 
echo "Players of albania are: <br>"; 

foreach ($json_output as $trend) 
{ 
    $id = $trend->ID; 
    echo " Name : {$trend->Name}\n";  
    echo '<br>'; 
} 
+2

你已經給出了URL和代碼是什麼問題? – StackB00m

+0

@ StackB00m我想訂購公民軍銜 –

+0

@ StackB00m你可以給我一個代碼片段嗎?我有點兒小菜! –

回答

0

an example on the usort docs排序多維數組。基本上只是取代你想要的數組索引'MilitaryRank'

我也爲了使它更具可讀性而多了一點HTML。

<form method="post"> 
    <input type="text" name="id"><br> 
    <input type="submit"> 
</form> 
<?php 
$okey= $_POST["id"];; 
$jsonurl="https://www.erevollution.com/en/api/citizenship/".$okey; 
$json = file_get_contents($jsonurl,0,null,null); 
$json_output = json_decode($json, true); 

// print_r($json_output); 

function cmp($a, $b) 
{ 
    if ($a['MilitaryRank'] == $b['MilitaryRank']) { 
     return 0; 
    } 
    return ($a['MilitaryRank'] < $b['MilitaryRank']) ? -1 : 1; 
} 

usort($json_output, "cmp"); 

echo "<h1>Players of albania are: </h1>"; 

foreach ($json_output as $trend) 
{ 
    $id = $trend['ID']; 
    echo " Name : $trend[Name]\n<br>"; 
    echo " MRank : $trend[MilitaryRank]\n<br><hr/>"; 
} 
+0

謝謝!這是我正在尋找的那個 –

1

json_decode API響應,使用true用於第二參數來獲取一個關聯數組,而不是一個對象stdClass的。

$json_output = json_decode($json, true); 

然後你可以使用usort通過MilitaryRank排序:

usort($json_output, function($a, $b) { 
    if ($a['MilitaryRank'] < $b['MilitaryRank']) return -1; 
    if ($a['MilitaryRank'] > $b['MilitaryRank']) return 1; 
    return 0; 
}); 

如果你想降序排序,而不是上升,只是反轉兩個if條件。

0
$json_decoded = json_decode($json,true); 

$allDatas = array(); 
foreach ($json_decoded as $user) { 
    $allDatas[$user['MilitaryRank']][] = $user; 
} 
sort($allDatas); 
print_r($allDatas); 

所以你可以做一個foreach這樣的:

foreach ($allDatas as $MilitaryRank => $users) { 
    # code... 
} 
0

這裏是我的解決方案,如果我這樣做是正確的,否則,指正!

<?php 
$jsonurl="https://www.erevollution.com/en/api/citizenship/1"; 
$json = file_get_contents($jsonurl,0,null,null); 
$json_output = json_decode($json, true); 
echo '<pre>'; 
echo "Players of albania are: <br>"; 
$military_rank = []; 
foreach ($json_output as $trend) 
{ 
    $military_rank[$trend['MilitaryRank']][] = $trend; 
} 
ksort($military_rank); 
foreach ($military_rank as $key => $rank) 
{ 
    echo '<br><br>Rank ' . $key . '<br>'; 
    foreach ($rank as $player) 
    { 
     echo 'Name: ' . $player['Name'] . '<br>'; 
    } 
}