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

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

4 Answers 4

2

Sorting an associative array in PHP

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.)

Comments

-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

1 Comment

Using eval is not (and should never be) necessary!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.