I am working on a crytomining page that shows all the miners that are active. Right now, it's displaying from an API in PHP:
<table >
<tr><th colspan="3">Connected Miners (POOL)</th></tr>
<tr><td >Miners Address</td><td >Shares</td><td >Miners Hashrate</td></tr>
<?php
$poolminers = json_decode(file_get_contents("<<API LINK>>"), false);
foreach ($poolminers->body->primary->shared as $miners) {
echo '<tr><td><a href=<<LINK>>?wallet=' . $miners->worker . '>' . $miners->worker . '</a></td>';
echo '<td>' . round($miners->shares, 2) . '</td><td>';
if ($miners->hashrate / 1000000 < 1000) {
echo round($miners->hashrate / 1000000, 3) . ' MH/s</td></tr>';
}
if ($miners->hashrate / 1000000 > 1000) {
echo round($miners->hashrate / 1000000000, 3) . ' GH/s</td></tr>';
}
}
?>
</table>
I want to sort by the miner's hashspeed, but I'm unsure how to sort by the "next" value. I tried putting $poolminers into an array, but I received a fatal error for -
Fatal error: Can't use function return value in write context
Side note - the owner of the site does not want the site info given out, so I add <<>> where the actual links are - sorry for any confusion.
So after reading the first answer, I'm wondering if maybe my issue is not so much the sorting (although that is the primary concern) but more of how do I convert an API's data into a multi-dimensional array?
CodePudding user response:
You can use usort
function to make this happen: usort
This code should sort your data by hashrate in ascending order:
$json = '[{"hashrate":50},{"hashrate":10},{"hashrate":35},{"hashrate":20}]';
$poolminers = json_decode($json, false);
usort($poolminers, function ($a, $b) {
return $a->hashrate <=> $b->hashrate;
});
foreach ($poolminers as $miners) {
echo $miners->hashrate . PHP_EOL;
}
Output:
10
20
35
50
If you would like to sort by descending order just swap $a and $b like this:
usort($poolminers, function ($a, $b) {
return $b->hashrate <=> $a->hashrate;
});