Zain Sohail
Zain Sohail

Reputation: 464

Sorting array with multiple values compared

I have the following array

$postarray[] = array( 'total'   => '6.5', 'points'  => '300' );
$postarray[] = array( 'total'   => '11.4', 'points' => '320' );
$postarray[] = array( 'total'   => '6.5', 'points'  => '340' );
$postarray[] = array( 'total'   => '2.6', 'points'  => '300' );
$postarray[] = array( 'total'   => '12.8', 'points' => '320' );

And I want to sort it into the following. Notice that if the points are equal then it compares total and sorts it in ascending order.

$postarray[] = array( 'total'   => '6.5', 'points'  => '340' );
$postarray[] = array( 'total'   => '12.8', 'points' => '320' );
$postarray[] = array( 'total'   => '11.4', 'points' => '320' );
$postarray[] = array( 'total'   => '6.5', 'points'  => '300' );
$postarray[] = array( 'total'   => '2.6', 'points'  => '300' );

So far I have used usort to sort according to the points but I'm not sure how to sort the total field too.

    function sortByOrder($a, $b) {
        if ($b['points'] > $a['points']) {
            return $b['points'] - $a['points'];
        } elseif ($b['points'] == $a['points']) {
            return 0;
        }
    }
    usort($postarray, 'sortByOrder');

Upvotes: 1

Views: 66

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

array_multisort() with array_column() as of PHP 5.5.0:

array_multisort(array_column($postarray, 'points'), SORT_DESC,
                array_column($postarray, 'total'),  SORT_DESC,
                $postarray);

Upvotes: 4

capcj
capcj

Reputation: 1535

You can use an example provided into sort example by php.net:

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

$postarray[] = array( 'total'   => '6.5', 'points'  => '300' );
$postarray[] = array( 'total'   => '11.4', 'points' => '320' );
$postarray[] = array( 'total'   => '6.5', 'points'  => '340' );
$postarray[] = array( 'total'   => '2.6', 'points'  => '300' );
$postarray[] = array( 'total'   => '12.8', 'points' => '320' );

 print_r(array_sort($postarray, 'points', SORT_DESC));

Upvotes: 1

Related Questions