Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array:

   array(2) {
      [0]=>  array(17) {
        [0]=>   int(40)
        [1]=>   int(41)
        [2]=>   int(199)
        [3]=>   int(196)
        ...etc...
     }
     [1]=>  array(17) {
        [0]=>   22
        [1]=>   66
        [2]=>   12
        [3]=>   180
        ...etc...
     }
   }

I want to sort the array by the second dimension in descending order so that the first dimension is also sorted and maintains the same 'association' by index. The results I want are instead:

   array(2) {
      [0]=>  array(17) {
        [0]=>   int(196)
        [1]=>   int(41)
        [2]=>   int(40)
        [3]=>   int(199)
        ...etc...
     }
     [1]=>  array(17) {
       [0]=>   180
       [1]=>   66
       [2]=>   22
       [3]=>   12
   ...etc...
     }
   }

(I hope I did that correctly.) Yes, I know I can extract these into row->col format and then use array_multisort but there -has- to be a way to do this more elegantly/directly, right? I'm clearly not getting it.

share|improve this question
    
I don't understand what you want to do - 196, 41, 40, 199 doesn't look sorted to me? –  Emily Shepherd Apr 2 at 18:48
    
It's the second dimension a[1]. It's sorted descending 180,66,22,12. And the members of a[0] then are re-ordered to maintain the same 'relationship'. –  jchwebdev Apr 2 at 18:51

1 Answer 1

Try:

foreach ($arrays as &$array) {
    sort($array);
}

Since we loop through each array in your array of array using the foreach. We can sort it like sorting any other array.

e: Sorry, I forgot that you need to add the ampersand to pass the array by reference.

e2: Use arsort instead of sort to sort in descending order.

share|improve this answer
    
Nope. Obviously this is more difficult than I thought. One needs to simultaneously sort a[1] and move the matching item from a[0] to the same new position. –  jchwebdev Apr 3 at 19:14

Your Answer

 
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.