skip to Main Content

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 class="selection">
<?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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search