2

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?

david
  • 3,225
  • 9
  • 30
  • 43
Elitmiar
  • 35,072
  • 73
  • 180
  • 229
  • possible duplicate of [PHP sort multidimensional array by value](http://stackoverflow.com/questions/2699086/php-sort-multidimensional-array-by-value) – jtbandes Apr 12 '12 at 11:33

5 Answers5

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

kjagiello
  • 8,269
  • 2
  • 31
  • 47
2

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

Josh
  • 10,961
  • 11
  • 65
  • 108
akamike
  • 2,148
  • 13
  • 16
0

This would help - http://www.informit.com/articles/article.aspx?p=341245&seqNum=7

Darmen Amanbay
  • 4,869
  • 3
  • 29
  • 50
0

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
  • 8,581
  • 10
  • 49
  • 66
-1

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 */
david
  • 3,225
  • 9
  • 30
  • 43
xkeshav
  • 53,360
  • 44
  • 177
  • 245