up vote 0 down vote favorite
share [fb]

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

link|improve this question

1  
Why do you ask a question that is copy-pasted from the PHP docs (Example #3) and already has a solution? – jensgram Mar 22 '11 at 11:57
feedback

closed as exact duplicate by Col. Shrapnel, Pascal MARTIN, jensgram, salathe, sixlettervariables Mar 22 '11 at 16:20

This question covers exactly the same ground as earlier questions on this topic; its answers may be merged with another identical question. See the FAQ.

4 Answers

up vote 2 down vote accepted

Sorting an associative array in PHP

link|improve this answer
Should be a comment. – Czechnology Mar 22 '11 at 11:49
feedback

usort() with the following comparison function:

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

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

link|improve this answer
feedback

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

link|improve this answer
feedback

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

link|improve this answer
1  
Using eval is not (and should never be) necessary! – fire Mar 22 '11 at 11:56
feedback

Not the answer you're looking for? Browse other questions tagged or ask your own question.