bxN5 bxN5 - 29 days ago 9
PHP Question

Usort sort multidimensional array by duplicate values

I have an array

[0] => ['name' => John, city => NY, street => WallStreet ..some anouther fields]
[1] => ['name' => Bill, city => FI, street => smstr.. some anouther fields]
[2] => ['name' => John, city => NY, street => WallStreet ..some anouther fields]
[3] => ['name' => Bill, city => FI, street => smstr ..some anouther fields]
[4] => ['name' => 4, city => 4, street => 4 ..some anouther fields]


I need to sort it to get all duplicate name city and street fields to be on the top of array or just in sequence

what I want

[] => ['name' => John, city => NY, street => WallStreet..some anouther fields]
[] => ['name' => John, city => NY, street => WallStreet ..some anouther fields]
[] => ['name' => Bill, city => FI, street => smstr ..some anouther fields]
[] => ['name' => Bill, city => FI, street => smstr ..some anouther fields]
[] => ['name' => 4, city => 4, street => 4 ..some anouther fields]


I'm trying use usort

usort($sorted, function($a, $b) {
if ($a['name'] == $b['name'] &&
$a['city'] == $b['city'] &&
$a['street'] == $b['street']
){
return 1;
}
else {
return -1;
}
});


but it's does not work, can anybody propose the solution?

p/s I'm working with php 5.3 :(

Answer Source

You can map to an array imploding the values, sort that descending and sort the original by that array:

array_multisort(array_map(function($v) {
                              return implode('-', $v);
                          }, $array), 
                SORT_DESC, $array);

This will work for all of the elements in the arrays. If for whatever reason you only want name, city and street, then replace the return with:

return $v['name'].'-'.$v['city'].'-'.$v['street'];