Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach Sorting

Tags:

php

sorting

I'm not too sure if this is possible but I will try to explain it anyhow,

We are trying to make a page for our guild and we want it to display the Average Item level Equipped along with their name e.g.

Name | iLvL 
Bob    262
Sam    159

We are currently running a script that is doing the following :

$members = $guild->getMembers();

This basically gets a list of all members in our guild - We are then iterating through with a foreach loop and making another call to get bits of information

//Character Arrays
foreach($members as $member) {

//Get character information
$mrank = $member['rank'];
$mname = $member['character']['name'];
$mgender = $member['character']['gender'];
$mlevel = $member['character']['level'];
$mrace = $member['character']['race'];
$character = $armory->getCharacter($mname);
$gear = $character->getGear();
$milevel = $gear['averageItemLevelEquipped'];
echo '<td><div align="center" class="style1">'. $mname .'</div></td>';
echo '<td><div align="center" class="style1">'. $milevel .'</div></td> ';

The only problem is because we iterate through them singular im not too sure how I could sort the Average Item Level into highest to lowest - I've heard of things like rsort but i couldn't seem to get it to work and I was wondering if anyone would be able to lend a hand with this.

Thanks

like image 584
DA-Dan Avatar asked Dec 09 '25 03:12

DA-Dan


2 Answers

I recommend creating an array out of the data you have there, with a sub-array for each person. Also create an array merely consisting of the averageItemLevelEquipped values, and then use that as the index array when runnning array_multisort. It would look something like this:

$resourcearray = array();
$indexarray = array();

foreach($members as $member) {
    //Get character information
    $mrank = $member['rank'];
    $mname = $member['character']['name'];
    $milevel = $gear['averageItemLevelEquipped'];
    //and anything else you want to add goes here, of course
    array_push($resourcearray, array('rank' => $mrank, 'charname' => $mname, 'itemlevel' => $milevel));
    array_push($indexarray, $milevel);
}

array_multisort($indexarray, $resourcearray);

foreach($resourcearray as $resource) {
    echo '<td><div align="center" class="style1">'. $resource['charname'] .'</div></td>';
    echo '<td><div align="center" class="style1">'. $resource['itemlevel'] .'</div></td> ';
}
like image 191
Joost Avatar answered Dec 11 '25 21:12

Joost


You can sort members in your SQL-query. If you want sort result array use uasort: http://www.php.net/manual/en/function.uasort.php

like image 29
merkushin Avatar answered Dec 11 '25 22:12

merkushin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!