2012-11-09 31 views
0

我正在嘗試添加特定變量(gq_numplayers)並將其顯示出來。如果數組在數組中,我該怎麼做? 如果你不明白髮生了什麼,我正在使用GameQ(https://github.com/Austinb/GameQ/)。將數組中的數值相加

編輯: var_dump($ results); http://pastebin.com/BSeeWMEb

<?php 
// Include the main class file 
require '../GameQ.php'; 

// Define your servers, 
// see list.php for all supported games and identifiers. 
$servers = array(
    array(
     'id' => 'server 1', 
     'type' => 'css', 
     'host' => '216.52.148.30', 
    ), 
    array(
     'id' => 'server 2', 
     'type' => 'css', 
     'host' => '216.52.143.83', 
    ), 
    array(
     'id' => 'server 3', 
     'type' => 'teamspeak3', 
     'host' => 'voice.xenogamers.org:8730', 
    ) 
); 

// Init the class, only need this once 
$gq = new GameQ(); 
$gq->addServers($servers); 

//optional settings 
$gq->setOption('timeout', 3); // Seconds 
$gq->setOption('debug', TRUE); 

// You can optionally specify some output filters, 
// these will be applied to the results obtained. 
$gq->setFilter('normalise'); 

// Send requests, and parse the data 
$results = $gq->requestData(); 

//make total 
$total = array_sum(?!?!?!??!?!?); 

echo $results['server 1']['gq_numplayers']; 
?> 
+1

我看不出gq_numplayers填充 – 2012-11-09 03:29:00

+0

貌似gq_numplayers必須根據requestData進行計算。如果是這樣,var_dump $結果並將其添加到問題。 – janenz00

回答

0

通過服務器只是環和球員的數量添加到正在運行總。

$num_players = 0; 
foreach ($results as $server) { 
    $num_players += (int)$server['gq_numplayers']; 
} 
0

如果$ ArrayA裏有$ ArrayB,那麼你需要一個循環。遍歷$ ArrayA用foreach這樣的:

的foreach($ ArrayA爲$項目){

}

在該循環中,你需要添加代碼在$項目運作。所以每次循環迭代時,$ item都將成爲數組中的下一個項目!您可以在進入循環之前聲明一個變量,例如$ counter,將它們全部添加。

但我也注意到你表明了這一點: echo $ results ['server 1'] ['gq_numplayers'];這個數組不是數組中的數組。這是一個單一的二維數組。所以我的答案甚至不會直接適用於它。你必須稍微改變一下循環。

0

你可以嘗試通過array_walk()自己添加它。

我不知道有關的RequestData()調用後的結果$結構,但是讓我們假設它看起來像下面的示例陣列:

<?php 
$results= array(
     array(
     'something'  => 'text', 
     'gq_numplayers' => 1, 
     ), 
     array(
     'something'  => 'text', 
     'gq_numplayers' => 2, 
     ), 
     array(
     'something'  => 'text', 
     'gq_numplayers' => 3, 
     ), 
    ); 
$total=0; 
array_walk($results,function($value,$key) use(&$total) { 
    $total+=(int)$value['gq_numplayers']; 
}); 
print $total."\n";