Thijmen van Doorn
Thijmen van Doorn

Reputation: 131

Foreach loop shows only the last row

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;
    }
?>

Upvotes: 1

Views: 555

Answers (1)

robni
robni

Reputation: 1066

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.

Upvotes: 1

Related Questions