Reputation: 1430
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 on php 5.3 , can anybody propose the solution?
p/s I'm working with php 5.3 :(
Upvotes: 1
Views: 234
Reputation: 78994
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);
To break it out and understand the pieces:
// Build an array of the values in each sub array
// John-NY-WallStreet
$sorter = array_map(function($v) { return implode('-', $v); }, $array);
print_r($sorter);
// Sort that descending sorting the original array the same
array_multisort($sorter, 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'];
Upvotes: 3