Support

Account

Home Forums Add-ons Repeater Field Order repeater rows by date

Solving

Order repeater rows by date

  • Hi, im trying to order rows from a repeater by date, but I need to highlight every date.

    The code I founded:

    <?php 
    
            // get repeater field data
            $repeater = get_field('actividad_diaria');
            // vars
            $order = array();
            // populate order
            foreach( $repeater as $i => $row ) {         
              $order[ $i ] = $row['date'];         
            }
            // multisort
            array_multisort( $order, SORT_DESC, $repeater );
            // loop through repeater
            if( $repeater ): ?>
              <ul>
              <?php foreach( $repeater as $i => $row ): ?>
                <li><?php echo $row['actividad']; ?>. <?php echo $row['aula']; ?>. <?php echo $row['hora_de_inicio']; ?> - <?php echo $row['hora_de_fin']; ?> </li>
              <?php endforeach; ?>
              </ul>
            <?php endif; ?>

    I get a list like this (ordered correctly by date):

    Dibujo. Aula 4. 09:00:00 – 10:00:00
    Dibujo. Aula 3. 09:00:00 – 10:00:00
    Dibujo. Aula 3. 10:00:00 – 11:00:00
    Ingés. Aula 3. 11:30:00 – 12:30:00
    Historia Aula 3. 12:30:00 – 13:30:00
    Geografía. Aula 3. 13:30:00 – 14:30:00
    Matemeticas. Aula 3. 12:00:00 – 13:00:00

    However I need a list like:

    YYYYMM01

    • Dibujo. Aula 4. 09:00:00 – 10:00:00
    • Dibujo. Aula 3. 09:00:00 – 10:00:00
    • Dibujo. Aula 3. 10:00:00 – 11:00:00

    YYYYMM02

    • Ingés. Aula 3. 11:30:00 – 12:30:00
    • Historia Aula 3. 12:30:00 – 13:30:00
    • Geografía. Aula 3. 13:30:00 – 14:30:00

    YYYYMM03

    • Matemeticas. Aula 3. 12:00:00 – 13:00:00

    If someone could help, I would be very grateful!
    Thank you!

  • You can construct a custom array after the sorted array.

    
    ... 
    array_multisort( $order, SORT_DESC, $repeater );
    
    $actual_loop = [];
    
    foreach ($repeater as $row) {
        // if this is a new date, we create a new array item
        if (! isset($actual_loop[$row['date']])) {
            $actual_loop[$row['date']] = [
                'date' => $row['date'],
                'rows' => []
            ];
        }
    
        $actual_loop[$row['date']]['rows'][] = $row;
    }
    
    foreach ($actual_loop as $loop) {
        echo '<h3>' . $loop['date'] . '<h3>';
        ecoh '<ul>';
    
        foreach ($loop['rows'] as $row) {
            echo "<li>{$row['actividad']}. {$row['aula']}. {$row['hora_de_inicio']} - {$row['hora_de_fin']}</li>";
        }
    
        echo '</ul>';
    }
    

    Cheers

  • Hi,
    Is it possible to display different outputs/formats for the date?

    This snippet works great but I would like to show Year and Month separately.

    Is it possible?

    Thanks

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.