Let’s say we have an array like that

array(2) {
  [2012]=>
  array(2) {
    [0]=>
    array(2) {
      ["file"]=>
      string(3) "aaa"
      ["mtime"]=>
      int(1347534106)
    }
    [1]=>
    array(2) {
      ["file"]=>
      string(3) "bbb"
      ["mtime"]=>
      int(1346293592)
    }
  }
  [2011]=>
  array(2) {
    [0]=>
    array(2) {
      ["file"]=>
      string(3) "ccc"
      ["mtime"]=>
      int(1316753224)
    }
    [1]=>
    array(2) {
      ["file"]=>
      string(3) "ddd"
      ["mtime"]=>
      int(1318671936)
    }
  }
}

I want this array to be sorted descending by first index (2012,2011[,2010,…]) and every subarray (every value of the root array) sorted descending by mtime values, but I cannot get how to apply array_multisort() to this. I could pass first key as '2012' and then it would be passed as a key of an associative array, but how to sort by mtime then?

share|improve this question

44% accept rate
feedback

1 Answer

up vote 0 down vote accepted

Given your toplevel array is $array, you can do like this:

krsort($array);
foreach ($array as &$arr) {
    uasort($arr, 'cmp');
}

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

var_dump($array); //to check results

that should do what you want.

Update: changed ksort for krsort for obtaining the descendin years as OP wanted.

share|improve this answer
I was testing right now and wondering why is it upside down :) Works perfect, but I just wanted to know, is array_multisort() applicable to this example or not? Reading php.net I was sure that this function is kind of ‘the only proper’ to sort multidimensional arrays. – user685107 yesterday
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

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