Skip to content
Advertisement

Sort a 2d array by its name column but ignoring the names’ prefixes

I want to sort an array of rows by the name column value, but critically I want to sort while ignoring the users’ prefixes.

Sample array:

$ad_users = [
    ["name" => "Mr San", "department" => "five"],
    ["name" => "Mr VSan", "department" => "six"],
    ["name" => "Mr QSan", "department" => "four"],
    ["name" => "Sr ASan", "department" => "two"],
    ["name" => "Dr ASan", "department" => "one"],
    ["name" => "Dr FSan", "department" => "three"]
];

Desired result:

[
    ["name" => "Dr ASan", "department" => "one"],
    ["name" => "Sr ASan", "department" => "two"],
    ["name" => "Dr FSan", "department" => "three"],
    ["name" => "Mr QSan", "department" => "four"],
    ["name" => "Mr San", "department" => "five"],
    ["name" => "Mr VSan", "department" => "six"]
]

My current code:

for ($x = 0; $x < count($ad_users); $x++) {
    $ad_users[$x]['name']= ucwords($ad_users[$x]['name']);
    $end = (explode(',', $ad_users[$x]['name']));
    $lastname = array_pop($end);
    sort($end);
    $firstname = implode(" ", $end);
    $ad_users[$x]['name']=$lastname." ".$firstname;
}
sort($ad_users);
for ($x = 0; $x < count($ad_users); $x++) {
    echo $ad_users[$x]['name']."n";
}

Advertisement

Answer

You make it clear in your comment that you originally have the name as firstname lastname, title, so you just need to sort first, then move the title to the front:

<?php
sort($ad_users);

// I've copied this section as-is, it looks like it could be improved
// but I can't be sure I'm making the correct improvements without seeing
// the original data
for ($x = 0; $x < count($ad_users); $x++) {
    $ad_users[$x]['name']= ucwords($ad_users[$x]['name']);
    $end = (explode(',', $ad_users[$x]['name']));
    $lastname = array_pop($end);
    sort($end);
    $firstname = implode(" ", $end);
    $ad_users[$x]['name']=$lastname." ".$firstname;
}

for ($x = 0; $x < count($ad_users); $x++) {
    echo $ad_users[$x]['name']."n";
}
?>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement