0

I have an array of arrays in PHP that I created like the following:

$wp_players = array();
 while ($wp_player = mysql_fetch_array($wp_player_query))
    {
        $wp_player_ranking = mysql_query(get_ranking_sql($wp_player['id'])) or die(mysql_error());
        $wp_ranking = mysql_fetch_array($wp_player_ranking);
        array_push($wp_players, array('first_name' => $wp_player['first_name'],
                     'last_name' => $wp_player['last_name'],
                     'school_name' => $wp_player['school_name'],
                     '1st' => $wp_ranking['1st'],
                     '2nd' => $wp_ranking['2nd'],
                     '3rd' => $wp_ranking['3rd'],
                     '4th' => $wp_ranking['4th'],
                     '5th' => $wp_ranking['5th'],
                     'total' => ($wp_ranking['1st'] + $wp_ranking['2nd'] + $wp_ranking['3rd'] + $wp_ranking['4th'] + $wp_ranking['5th'])));
    }

What I want to do now is have $wp_players array sorted by the 'total' key that's inside each of its elements. Since the Array is not flat, and is an array of arrays, what's the best way to do this in PHP?

randombits
  • 47,058
  • 76
  • 251
  • 433
  • 1
    [`usort`](http://php.net/usort). Also, you can simplify your code greatly. `$wp_ranking['total'] = $wp_ranking['1st']+.....; $wp_players[] = $wp_ranking;` – Niet the Dark Absol Nov 26 '13 at 01:40

2 Answers2

2

array_multisort() will accomplish precisely what you're looking to achieve:

$totals = array();
foreach ($wp_players as $key => $row) {
    $totals[$key] = $row['total'];
}
array_multisort($totals, SORT_DESC, $wp_players);
zeantsoi
  • 25,857
  • 7
  • 69
  • 61
0

This function will be what you want, this function if from my development framework, It suits for many situations, has order control and reserveKey control parameters.

<?php
function sortByField($arr, $fieldName, $flag = 'desc', $reserveKey = true)
{
    $indexArr = array();
    foreach ($arr as $idx => $item)
    {
        $indexArr[$idx] = $item[$fieldName];
    }

    if ('desc' == $flag)
    {
        arsort($indexArr);
    }
    else
    {
        asort($indexArr);
    }

    $result = array();
    foreach ($indexArr as $idx => $field)
    {
        if($reserveKey)
        {
            $result[$idx] = $arr[$idx];
        }
        else
        {
            $result[] = $arr[$idx];
        }
    }
    return $result;
}

usage

 $wp_players = sortByField($wp_players, 'total');
srain
  • 8,944
  • 6
  • 30
  • 42
  • Seems a bit overkill for a simple task. `usort($wp_players,function($a,$b) {return $a['total']-$b['total'];});` would do the job just fine. – Niet the Dark Absol Nov 26 '13 at 01:40
  • For this issue, you are right, `usort()` is simple enough. This function if from my development framework, It suits for many situations, has `order control` and `reserveKey control` parameters. – srain Nov 26 '13 at 01:44