Foreach loop shows only the last row

Issue

I created an email placeholder (#_DATATABEL) for the plugin Events Manager. This placeholder must show the repeater fields from customized fields from Advanced Custom Fields Pro.

In this case, the loop shows only the last row. There are four rows/results in total.

How can I fix this?

<?php
    //
    // Create new placeholder | events manager email
    //
    add_filter('em_event_output_placeholder', 'datatable_placeholders', 1, 3);
    function datatable_placeholders($replace, $EM_Event, $result) {
        if($result == '#_DATATABEL') {
            $current_event_id = $EM_Event->output("#_EVENTPOSTID");
            $replace = 'none';
            //$EM_Event = new EM_Event($cursus_id);

            $replace = create_data_table_mail($current_event_id);
        }
        return $replace;
    }

    function create_data_table_mail($current_event_id) {
        if(get_field('gekoppelde_cursus_leergang', $current_event_id)) {

            $loop = get_field('gekoppelde_cursus_leergang', $current_event_id);
            foreach($loop as $sub_field) {
                $resultaat = $sub_field['cursus_leergang'];
            }
        }
        return $resultaat;
    }
?>

Solution

function create_data_table_mail($current_event_id) {
    if(get_field('gekoppelde_cursus_leergang', $current_event_id)) {

        $loop = get_field('gekoppelde_cursus_leergang', $current_event_id);
        $arr = array();
        foreach($loop as $sub_field ) {
            $arr[] = $sub_field['cursus_leergang'];
        }
    }
    return $arr;

Your foreach loop iterates through all items from $sub_field and overrides $resultaat every time. After that, you return the last $resultaat. Try to use a list or an array and add the results to it, and then return the list or array.

Answered By – robni

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published