'Categorize foreach loop results with subheaders

I am displaying the result of a repeater field (wordpress/acf) with the following code :

<?php 
$rows = get_field('resa_table');
if( $rows ) { 

echo '<table>';

foreach( $rows as $row ) {
$name = $row['name']; 
$department = $row['department']; 
?>

<tr>
    <td><?php echo $name; ?></td>
    <td><?php echo $department; ?></td>
</tr>

<?php } echo '</table>'; } ?>

I would like - at least - to sort the results by "department" values. I looked it up on other threads and it doesn't seem too complicated.

I haven't tried it yet though, because what I want to do is a little more complex : I would like to categorize the results by position values AND add a header row before each new "department", in order to get to this result :

<table>
<tr class="department"><td>Marketing</td></tr>
<tr><td>John</td></tr>
<tr><td>Mary</td></tr>
<tr class="department"><td>Finance</td></tr>
<tr><td>Jack</td></tr>
<tr><td>Jane</td></tr>
</table>

Is this doable ?



Solution 1:[1]

I make one array like yours data and try make what you want.. Here php codes;

        <?php

    $rows =  array(
        array("name" => "jhon", "department" => "Marketing"),
        array("name" => "mary", "department" => "Marketing"),
        array("name" => "Jack", "department" => "Finance"),
        array("name" => "Jane", "department" => "Finance")
    );    

    // update 
    // these codes will sort the array by department.
    $department = array_column($rows, 'department');
    array_multisort($department, SORT_DESC, $rows);
    // update

    if ($rows) {
        echo '<table>';
        $check_department = "";

        foreach ($rows as $row) {
            $name = $row['name'];
            $department = $row['department'];

            if ($check_department !=  $department) {
                $check_department  = $row['department'];
                echo "<tr class=\"" . $department . "\"><td>" . $department . "</td></tr>";
            } else {
            }
    ?>
            <tr>
                <td><?php echo $name; ?></td>
            </tr>
    <?php

        }
        echo '</table>';
    } ?>

This codes result is;

     <table>
     <tr class="Marketing"><td>Marketing</td></tr>                
     <tr><td>jhon</td></tr>
     <tr><td>mary</td></tr>
     <tr class="Finance"><td>Finance</td></tr>                
     <tr><td>Jack</td></tr>
     <tr><td>Jane</td></tr>
     </table>

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1