views:

71

answers:

4

I have an array like the following:

Array
(
    [0] => Array
        (
            'name' => "Friday"
            'weight' => 6
        )
    [1] => Array
        (
            'name' => "Monday"
            'weight' => 2
        )
)

I would like to grab the last values in that array (the 'weight'), and use that to sort the main array elements. So, in this array, I'd want to sort it so the 'Monday' element appears before the 'Friday' element.

+7  A: 

You can use usort as:

function cmp($a, $b) {
   return $a['weight'] - $b['weight'];
}

usort($arr,"cmp");
codaddict
You can simply use `return $a['weight'] - $b['weight'];`.
Gumbo
Ahhhhhhh! Nested ternary operators!
Rocket
@Gumbo: True..just realized that :)
codaddict
Hmm... looks like the way to go.
geerlingguy
+3  A: 

try this: http://php.net/manual/en/function.usort.php

PatrickS
A: 

Agree with usort, I also sometimes use array_multisort (http://ca2.php.net/manual/en/function.usort.php) example 3, sorting database results. You could do something like:

<?php
$days = array(
  array('name' => 'Friday', 'weight' => 6),
  array('name' => 'Monday', 'weight' => 2),
);

$weight = array();
foreach($days as $k => $d) {
  $weight[$k] = $d['weight'];
}

print_r($days);

array_multisort($weight, SORT_ASC, $days);

print_r($days);
?>

Output:

Array
(
    [0] => Array
        (
            [name] => Friday
            [weight] => 6
        )

    [1] => Array
        (
            [name] => Monday
            [weight] => 2
        )

)
Array
(
    [0] => Array
        (
            [name] => Monday
            [weight] => 2
        )

    [1] => Array
        (
            [name] => Friday
            [weight] => 6
        )

)
Maurice Kherlakian
A: 

Here's a cool function that might help:

function subval_sort($a,$subkey,$sort) {
    foreach($a as $k=>$v) {
        $b[$k] = strtolower($v[$subkey]);
    }
    if($b)
    {
        $sort($b);
        foreach($b as $key=>$val) {
            $c[] = $a[$key];
        }
        return $c;
    }
}

Send in the array as $a the key as $subkey and 'asort' or 'sort' for the $sort variable

d2burke