2013-12-21 32 views
1

一旦我得到這個代碼打印只在最後的foreach

$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最後一次,所以只能將再次顯示它(在它最後一次功能)。而不是每次它執行該功能。我會怎麼做?謝謝!

+0

我不認爲你粘貼完整的代碼。有缺少電話.. –

回答

-1

這意味着在最後一次迭代中調用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變量...

+0

我的意思是做echo $ totalcount;只有在最後一次調用print_result時。 –

+0

通過數組獲取最後一個元素並不是一個好的迭代。 – klipach

1

你可能不itarate全陣列,但只需要最後一個元素與end()功能,像這樣:

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