按assoc数组上的重复值对assoc数组进行排序

时间:2019-04-26 12:00:49

标签: php sorting php-7

我想通过特定键的重复值对数组进行排序: 我不想删除重复的项目,但是我只需要按重复的

排序我的数组

例如,我有这个数组:

$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"
    )
);

在我的代码中,我拥有一个assoc数组,可以按给定的键对它进行排序,而不会删除我需要的所有重复值 我怎样才能做到这一点 ? 谢谢

2 个答案:

答案 0 :(得分:0)

结合使用array_mutlisort()array_column()进行多维排序(以获取哪一列是排序的基础)。此功能仅供参考,因此您无需将结果分配回某些对象。

$data = array(...);
array_multisort(array_column($data, "name"), SORT_ASC, $data);
print_r($data);

答案 1 :(得分:0)

您可以使用usort

function compare($a, $b)
{
   if ($a["name"] == $b["name"]) {
    return 0;
   }
  return ($a["name"] < $b["name"]) ? -1 : 1;
}

usort($data,"compare");