0

I am trying to sort an array based on the first [0] child element. But in my code the keys are being replaced by the array number in the sort:

$myArray = array(
    'my last row' => array(  
         '0' => 'ZZZZ',
         '1' => 'AAAA'
     ),
     'the first row' => array(
         '0' => 'AAAA'
     )
  );
usort($myArray, 'cmp' ) ;

var_dump($myArray);

function cmp    ($a, $b)        {
        return ( ( $a[0] > $b[0] ) ? 1 : -1 );
}

result:

array(2) {
  [0]=>       // should be ['the first row']  *not* [0]
  array(1) {
    [0]=>
    string(4) "AAAA"
  }
  [1]=>        // should be ['my last row']  *not* [1]
  array(2) {
    [0]=>
    string(4) "ZZZZ"
    [1]=>
    string(4) "AAAA"
  }
}

The sort order itself appears to be working as expected.

I would like to see the following:

the first row  => AAAA
my last row   =>  ZZZZ, AAAA

This is probably a very simple issue, but I cannot resolve it.

Thank you very much.

EDIT: this sort does not involve the key itself, but rather a child-element key. i believe that makes this question unique.

5
  • Possible duplicate of Sort multidimensional array PHP Commented Jul 11, 2017 at 20:09
  • 1
    Possible duplicate of Keeping array index key when sorting a multidimensional array with PHP Commented Jul 11, 2017 at 20:22
  • "Don't Panic"'s suggestion of using "uasort" worked great, but he seemed to have removed his answer. if you want to put it out there again, i would be honored to select that as the correct one. Commented Jul 11, 2017 at 20:29
  • @edwardsmarkf I deleted it after I found what I thought was a duplicate. It still looks like a duplicate to me, to be honest. Maybe take a look at that one again? Their comparison function is different, but the main point of it is that they're having the same issue with the keys not being preserved. Commented Jul 11, 2017 at 20:34
  • Dont Panic - you are correct it was a duplicate, sorry. But your solution worked out great. Sadly, i have discovered this takes a HUGE performance hit, so i am looking into doing the sort on the client side instead. Commented Jul 11, 2017 at 23:21

1 Answer 1

0

Try this: It will maintain your index associations.

$myArray = array(
'my last row' => array(  
     '0' => 'ZZZZ',
     '1' => 'AAAA'
 ),
 'the first row' => array(
     '0' => 'AAAA'
 )

); asort($myArray);

print_r($myArray);

Array ( [the first row] => Array ( [0] => AAAA ) [my last row] => Array ( [0] => ZZZZ [1] => AAAA ) )

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.