Nikoljan Behari Nikoljan Behari - 3 months ago 31
JSON Question

Ordering json api with php

I have been curious about PHP lately and I am working on a test subject. I want to get the number of citizens from an online game and order it by Military rank.

Here is the link of the API: https://www.erevollution.com/en/api/citizenship/1

Here is the code I have so far.

<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>';
}

Answer

There's an example on the usort docs for sorting a multidimensional array. Basically just substitute your desired array index 'MilitaryRank'

I also zazzed up the HTML a little more to make it more readable.

<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/>";
}
Comments