vipz vipz - 13 days ago 5
PHP Question

how to usort an array which is already sorted with another key

my first array is already sorted by name,but i want to usort it with position,
what i have tried is here,
array before usort

Array
(
[0] => Array
(
[name] => admin
[designation] => admin
[email] => admin@admin
[phone] => 999777788
[ext] => 67767
[position] => 1
[image] =>
)

[1] => Array
(
[name] => ATeam
[designation] => Manager
[email] => service@mail.com
[phone] =>
[ext] => 777
[position] => 3
[image] =>
)

[2] => Array
(
[name] => BTeam
[designation] => Manager
[email] =>g@mail.co.in
[phone] =>
[ext] =>
[position] => 4
[image] =>
)

[3] => Array
(
[name] => hi team
[designation] => new
[email] => abc
[phone] => 3333
[ext] => 333
[position] => 10
[image] =>
)
[4] => Array
(
[name] => new team
[designation] => maneger
[email] => mg@g
[phone] => 445567676
[ext] => ext
[position] => 10
[image] =>
)


)

usort function i applied to the array is:

usort($a_teams,function($a,$b){
if($a['position'] == '') return 1;
if($b['position'] == '') return -1;
return $a['position']-$b['position'];
});


the result array is:

Array
(
[0] => Array
(
[name] => admin
[designation] => admin
[email] => admin@admin
[phone] => 999777788
[ext] => 67767
[position] => 1
[image] =>
)

[1] => Array
(
[name] => ATeam
[designation] => Manager
[email] => service@mail.com
[phone] =>
[ext] => 777
[position] => 3
[image] =>
)

[2] => Array
(
[name] => BTeam
[designation] => Manager
[email] => g@mail.co.in
[phone] =>
[ext] =>
[position] => 4
[image] =>
)

[3] => Array
(
[name] => new team
[designation] => maneger
[email] => mg@g
[phone] => 445567676
[ext] => ext
[position] => 10
[image] =>
)

[4] => Array
(
[name] => hi team
[designation] => new
[email] => abc
[phone] => 3333
[ext] => 333
[position] => 10
[image] =>
)

)


but the problem is the alphabetical order of
name
is not getting in proper order when the
positions
is same

Answer

Changed the usort function for sorting by position and name:

usort($a_specials,function($a,$b){
    if($a['position'] == '') return 1;
    if($b['position'] == '') return -1;
    if($a['position'] == $b['position'])
        return strnatcmp($a['title'],$b['title']);
    return $a['position']-$b['position'];

});