PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 20, 2022

[FIXED] How to sort API values in PHP

 January 20, 2022     api, php, sorting     No comments   

Issue

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 class="left">
        <tr><th colspan="3">Connected Miners (POOL)</th></tr>
        <tr><td class="header">Miners Address</td><td class="header">Shares</td><td class="header">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?


Solution

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



Answered By - Bartosz Brożek
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing