按关联数组上的重复值对关联数组进行排序
Sorting assoc array by duplicate value on assoc array
我想按特定键的重复值对数组进行排序:
我不想删除重复项,但我只需要按重复项对数组进行排序
例如我有这个数组:
$data = array(
array(
"id" => 1,
"name" => "Bruce Wayne",
"city" => "Gotham",
"gender" => "Male"
),
array(
"id" => 2,
"name" => "Diana Prince",
"city" => "Gotham",
"gender" => "Male"
),
array(
"id" => 4,
"name" => "Speedy Gonzales",
"city" => "New Mexico",
"gender" => "Male"
),
array(
"id" => 3,
"name" => "Diana Prince",
"city" => "New Mexico",
"gender" => "Female"
),
array(
"id" => 5,
"name" => "Bruce Wayne",
"city" => "Gotham",
"gender" => "Male"
),
);
我的回答是:
$data = array(
"id" => 1,
"name" => "Bruce Wayne",
"city" => "Gotham",
"gender" => "Male"
),
array(
"id" => 5,
"name" => "Bruce Wayne",
"city" => "Gotham",
"gender" => "Male"
),
array(
"id" => 2,
"name" => "Diana Prince",
"city" => "Gotham",
"gender" => "Male"
),
array(
"id" => 3,
"name" => "Diana Prince",
"city" => "New Mexico",
"gender" => "Female"
),
array(
"id" => 4,
"name" => "Speedy Gonzales",
"city" => "New Mexico",
"gender" => "Male"
)
);
在我的代码中,我有一个关联数组,我需要按给定的键对它进行排序,而不删除我需要的所有重复值
我怎样才能做到这一点 ?
谢谢
通过array_mutlisort()
结合array_column()
使用多维排序(取哪一列作为排序的依据)。这个函数是通过引用的,所以你不需要将结果赋值回某个东西。
$data = array(...);
array_multisort(array_column($data, "name"), SORT_ASC, $data);
print_r($data);
您可以使用usort
function compare($a, $b)
{
if ($a["name"] == $b["name"]) {
return 0;
}
return ($a["name"] < $b["name"]) ? -1 : 1;
}
usort($data,"compare");
我想按特定键的重复值对数组进行排序: 我不想删除重复项,但我只需要按重复项对数组进行排序
例如我有这个数组:
$data = array(
array(
"id" => 1,
"name" => "Bruce Wayne",
"city" => "Gotham",
"gender" => "Male"
),
array(
"id" => 2,
"name" => "Diana Prince",
"city" => "Gotham",
"gender" => "Male"
),
array(
"id" => 4,
"name" => "Speedy Gonzales",
"city" => "New Mexico",
"gender" => "Male"
),
array(
"id" => 3,
"name" => "Diana Prince",
"city" => "New Mexico",
"gender" => "Female"
),
array(
"id" => 5,
"name" => "Bruce Wayne",
"city" => "Gotham",
"gender" => "Male"
),
);
我的回答是:
$data = array(
"id" => 1,
"name" => "Bruce Wayne",
"city" => "Gotham",
"gender" => "Male"
),
array(
"id" => 5,
"name" => "Bruce Wayne",
"city" => "Gotham",
"gender" => "Male"
),
array(
"id" => 2,
"name" => "Diana Prince",
"city" => "Gotham",
"gender" => "Male"
),
array(
"id" => 3,
"name" => "Diana Prince",
"city" => "New Mexico",
"gender" => "Female"
),
array(
"id" => 4,
"name" => "Speedy Gonzales",
"city" => "New Mexico",
"gender" => "Male"
)
);
在我的代码中,我有一个关联数组,我需要按给定的键对它进行排序,而不删除我需要的所有重复值 我怎样才能做到这一点 ? 谢谢
通过array_mutlisort()
结合array_column()
使用多维排序(取哪一列作为排序的依据)。这个函数是通过引用的,所以你不需要将结果赋值回某个东西。
$data = array(...);
array_multisort(array_column($data, "name"), SORT_ASC, $data);
print_r($data);
您可以使用usort
function compare($a, $b)
{
if ($a["name"] == $b["name"]) {
return 0;
}
return ($a["name"] < $b["name"]) ? -1 : 1;
}
usort($data,"compare");