【问题标题】:Print only once on the last foreach在最后一个 foreach 上只打印一次
【发布时间】:2013-12-21 14:20:07
【问题描述】:

我得到了这个代码

$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>");
    }

我希望它只在最后一次执行 print_table 时回显,所以它只会显示一次(在最后一次执行该功能时)。并不是每次它都执行该功能。我该怎么做?谢谢!

【问题讨论】:

  • 我认为您没有粘贴整个代码。有漏接电话..

标签: php foreach echo


【解决方案1】:

您可能不会遍历整个数组,而是只使用 end() 函数获取最后一个元素,如下所示:

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

【讨论】:

    【解决方案2】:

    这意味着在最后一次迭代中调用 print_table ?然后试试:

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

    它还取决于 $id 值。 $id 值是相关的(0,1,2,3...)?所以你可以用 $id 替换 $curr 变量...

    【讨论】:

    • 我的意思是做 echo $totalcount;仅在最后一次调用 print_result 时。
    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 2014-01-07
    • 2021-07-03
    • 1970-01-01
    • 2020-09-01
    • 2021-06-11
    • 2020-12-09
    • 1970-01-01
    相关资源
    最近更新 更多