0

Possible Duplicate:
Sorting an associative array in PHP

Hello all,

I have an array like

<?php
    $data[] = array('id' => 67, 'hits' => 2);
    $data[] = array('id' => 86, 'hits' => 1);
    $data[] = array('id' => 85, 'hits' => 6);
    $data[] = array('id' => 98, 'hits' => 2);
    $data[] = array('id' => 89, 'hits' => 6);
    $data[] = array('id' => 65, 'hits' => 7);
 ?>

And I want to sort this array on the basis on hits.

Please suggest some code that help me....

Thanks in advance

Community
  • 1
  • 1
Pushpendra
  • 4,254
  • 3
  • 33
  • 64
  • 1
    Why do you ask a question that is copy-pasted from the [PHP docs](http://php.net/manual/en/function.array-multisort.php) (Example #3) *and* already has a solution? – jensgram Mar 22 '11 at 11:57

4 Answers4

2

Sorting an associative array in PHP

Community
  • 1
  • 1
Mark Nenadov
  • 5,403
  • 5
  • 21
  • 28
2

You need the usort() function - allows you to specify a custom compare function. See http://php.net/manual/en/function.usort.php.

Your compare function could for example be function cmp($a, $b) { return strcasecmp($a['edition'], $b['edition']); }

Victor
  • 2,941
  • 3
  • 21
  • 27
1

usort() with the following comparison function:

function cmpHits($a, $b) {
    return $a['hits'] - $b['hits'];
}

(Untested, uasort() if you want to maintain key associations.)

jensgram
  • 29,088
  • 5
  • 77
  • 95
-1

Try this:

array_multi_sort($data, array('edition'=>SORT_DESC));

function array_multi_sort($array, $cols)
{
    $colarr = array();
    foreach($cols as $col => $order)
    {
        $colarr[$col] = array();
        foreach ($array as $k => $row)
        {
            $colarr[$col]['_'.$k] = strtolower($row[$col]);
        }
    }

    $eval = 'array_multisort(';
    foreach($cols as $col => $order)
    {
        $eval .= '$colarr[\''.$col.'\'],'.$order.',';
    }
    $eval = substr($eval,0,-1).');';
    eval($eval);
    $ret = array();
    foreach($colarr as $col => $arr)
    {
        foreach($arr as $k => $v)
        {
            $k = substr($k,1);
            if (!isset($ret[$k])) $ret[$k] = $array[$k];
            $ret[$k][$col] = $array[$k][$col];
        }
    }
    return $ret;
}

Resource: http://php.net/manual/en/function.array-multisort.php

PHPology
  • 887
  • 5
  • 12