我最近对PHP感到好奇,而且我正在研究测试主题。我希望通过在线游戏获得公民人数并按军衔命名。
以下是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>';
}
答案 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
条件。
答案 1 :(得分: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...
}
答案 2 :(得分: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>';
}
}
答案 3 :(得分: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/>";
}