使用php订购json api
问题描述:
最近我一直对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>';
}
答
有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
谢谢!这是我正在寻找的那个 –
答
当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
条件。
答
$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...
}
答
这里是我的解决方案,如果我这样做是正确的,否则,指正!
<?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>';
}
}
你已经给出了URL和代码是什么问题? – StackB00m
@ StackB00m我想订购公民军衔 –
@ StackB00m你可以给我一个代码片段吗?我有点儿小菜! –