简体   繁体   中英

Print only once on the last foreach

I got this code

$servers = array(
         array(
            'type' => 'tf2', 
            'host' => '193.192.59.191:27015', 
        ),
        array(
            'type' => 'tf2', 
            'host' => '193.192.59.191:27025', 
        ),
        array(
            'type' => 'tf2', 
            'host' => '193.192.59.191:27035', 
        ),
        array(
            'type' => 'tf2', 
            'host' => '193.192.59.191:27045', 
        ),
        array(
            'type' => 'tf2', 
            'host' => '193.192.59.191:27055', 
        ),
        array(
            'type' => 'tf2', 
            'host' => '193.192.59.191:27065', 
        ),
        array(
            'type' => 'tf2', 
            'host' => '193.192.59.191:27075', 
        ),
);
$totalcount = 0;

    function print_results($results) {
        foreach ($results as $id => $data) {
            print_table($data);
        }
    }
    function print_table($data) {
            global $totalcount;
            $totalcount = $totalcount + $data['gq_maxplayers'];
            echo $totalcount;
        }


        if (!$data['gq_online']) {

        }
        printf("</tr></tbody>");
    }

And I want it to echo only in the last time it does print_table, So it will only display it once (in the last time it does the function). And not each time it does the function. How would I do that? Thanks!

You may not itarate full array, but take only last element with end() function, like this:

function print_result( $result ) {
  $end = end( $result );
  if ( $end !== false ) print_table( $end );
  reset ( $result ); // to recovery internal pointer
}

It means call print_table in the last iteration? Then try:

function print_results($results) {
    $total = count($results);
    $curr = 0;
    foreach ($results as $id => $data) {
        if ($curr == $total - 1) print_table($data);
        $curr++;
    }
}

It also depends on $id values. $id values are correlative (0,1,2,3...)? So you can replace $curr variable with $id...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM