Home > database >  How can I order these 2 foreach loops alphabetically
How can I order these 2 foreach loops alphabetically

Time:12-15

I have a foreach loop within a foreach loop the first foreach loop grabs the department the second foreach loop grabs the names within that department

<div >
<?php 
foreach ($departments as $department) {
  $code = $department['department_code'];
  $names = $department['department_names'];
  foreach ($names as $name) {
    $department_name = $name['name_of_department'];
    echo $department_name ;
  }
}
?>
</div>

currently the list sorts first by the department then the names which causes the alphabetical order to be broken, what can I add to make this code show the names in alphabetical order.

CodePudding user response:

Would this work?

    array_multisort(array_column($departments,'department_code'), SORT_ASC, SORT_STRING|SORT_FLAG_CASE,
                    array_column($departments,'department_names'), SORT_ASC, SORT_STRING|SORT_FLAG_CASE,
                    $departments);

That should put it in Code order then Name order where the Codes are the same

CodePudding user response:

You may use the php sort() method to order the names in alphabetical order:

...
$names = $department['department_names'];

sort($names); // This will sort the $names in alphabetical order

foreach ($names as $name) {
    $department_name = $name['name_of_department'];
    echo $department_name ;
}

Full code with the sort:

foreach ($departments as $department) {
    $code = $department['department_code'];
    $names = $department['department_names'];

    sort($names); // This will sort the $names in alphabetical order

    foreach ($names as $name) {
        $department_name = $name['name_of_department'];
        echo $department_name ;
    }
}

One tip: try moving this logic away from your view. It looks like you are adding this logic in a div tag, what is located in a view file.

Such logic does not belong in a view.

  • Related