0

i have array like this,

Array
(
  [341] => Array
    (
        [id] => 2034
        [name] => Basic
        [file] => 577688a31d889.svg
        [order] => 12
    )

  [342] => Array
    (
        [id] => 2065
        [name] => Bold
        [file] => 579af7d384970.svg
        [order] => 0
    )

  [344] => Array
    (
        [id] => 2036
        [name] => Modern
        [file] => 577688a37fe1b.svg
        [order] => 10
    )

  [1869] => Array
    (
        [id] => 2066
        [name] => Professional
        [file] => 579af7d3c0774.svg
        [order] => 0
    )

  [335] => Array
    (
        [id] => 2033
        [name] => Favourites
        [file] => 577688a2e0502.svg
        [order] => 0
    )

  [1870] => Array
    (
        [id] => 2067
        [name] => traditional
        [file] => 579af7d3f231a.svg
        [order] => 0
    )
)

I want to sort it by desc for order. But if order is same then sort it by its name asc. And i also want to keep key of array. i tried some solutions but not worked well for me and in some solutions it waived key.

usort($data, function($a, $b) { 
    $rdiff = $a['order'] - $b['order'];
    if ($rdiff) return $rdiff; 
     return $a['name'] - $b['name']; 
}); 

so according to given array, output should be like this, 341, 344, 342 335, 1869, 1870.

1
  • @NanaPartykar i updated my question Commented Jul 30, 2016 at 6:40

1 Answer 1

2

The solution using uasort and strcasecmp functions:

// $arr is your initial array
uasort($arr, function ($a, $b) {
    if ($a['order'] == $b['order']){
        return strcasecmp($a['name'], $b['name']);
    } else {
        return $b['order'] - $a['order'];
    }
});

print_r($arr);

DEMO link

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.