tags:

views:

120

answers:

5

I have the following array

[0] => Array
        (
            [id] => 229
            [val] => 2
        )

    [3] => Array
        (
            [id] => 237
            [val] => 1
        )

    [4] => Array
        (
            [id] => 238
            [val] => 6
        )

I need to sort this array according to the val values in the array, and do not know how to accomplish this?

+8  A: 
function cmp($a, $b)
{
    if ($a["val"] == $b["val"]) {
        return 0;
    }
    return ($a["val"] < $b["val"]) ? -1 : 1;
}

usort($yourarray, "cmp");

Read this for more information.

Balon
I would do: uasort($yourarray, 'cmp');to maintain keyvalue-pair (index association).
Pindatjuh
A: 

You can use array_multisort()

Examples here: http://www.php.net/manual/en/function.array-multisort.php

The Example #3 Sorting database results is what you want. Might be easier if you are not familiar with callback functions and usort().

Petr Peller
+2  A: 

array_multisort can help with this, example 3 presents a similar problem and solution.

akamike
A: 

use this function to sort array accroding to your need

function sksort(&$array, $subkey="id",$sort_ascending=false)

 {
    if (count($array))
        $temp_array[key($array)] = array_shift($array);

    foreach($array as $key => $val){
        $offset = 0;
        $found = false;
        foreach($temp_array as $tmp_key => $tmp_val)
        {
            if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
            {
                $temp_array = array_merge(    (array)array_slice($temp_array,0,$offset),
                                            array($key => $val),
                                            array_slice($temp_array,$offset)
                                          );
                $found = true;
            }
            $offset++;
        }
        if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
    }

    if ($sort_ascending) $array = array_reverse($temp_array);

    else $array = $temp_array;
}

========================================================================== now use this function in ur array

sksort($arrayname, "val"); /* for ascending */

sksort($arrayname, "val", true); /* for descending */
diEcho
why this is downvoted? would anybody tell me??
diEcho