0

I would like to sort an array by duplicate value of a specific key : I dont want to remove duplicate item but i just need to sort my array by duplicate

for exemple i have this 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"
    ),
);

what should i have as a response is :

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

In my code I have an assoc array i nedd to sort it by a given key without removing duplicate value that all what i need How can I do this ? thank you

1

2 Answers 2

0

Use multidimensional sorting through array_mutlisort() combined with array_column() (to fetch which column is the basis for sorting). This function is by reference, so you don't need to assign the result back to something.

$data = array(...);
array_multisort(array_column($data, "name"), SORT_ASC, $data);
print_r($data);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use usort

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

usort($data,"compare");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.