我有一个数组
[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]
我需要对其进行排序,以便将所有重复名称的城市和街道字段放在数组顶部或按顺序排列
我想要什么
[] => ['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]
我正在尝试使用usort
usort($sorted, function($a, $b) {
if ($a['name'] == $b['name'] &&
$a['city'] == $b['city'] &&
$a['street'] == $b['street']
){
return 1;
}
else {
return -1;
}
});
但它在php 5.3上不起作用,有人可以提出解决方案吗?
p / s我正在使用php 5.3 :(
答案 0 :(得分:2)
您可以映射到一个插入值的数组,按降序排序并按该数组对原始数据进行排序:
array_multisort(array_map(function($v) {
return implode('-', $v);
}, $array),
SORT_DESC, $array);
要打破它并理解这些碎片:
// 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);
这适用于数组中的所有元素。如果由于某种原因您只需要name
,city
和street
,请将return
替换为:
return $v['name'].'-'.$v['city'].'-'.$v['street'];