2016-11-22 74 views
0

我有一個值的數組,我需要對它們進行計數,但只有達到$目標數量。我需要知道需要多少數組鍵才能達到目標($ count)以及這些相應值的總和($ total)。下面是我使用的陣列:php - 如何統計數組值和密鑰,直到達到目標

$numbers = Array ([0] => 1 [1] => 1 [2] => 1 [3] => 1 [4] => 6 [5] => 1 [6] => 5.5 [7] => 1 [8] => 1 [9] => 1 [10] => 1 [11] => 1 [12] => 1 [13] => 11) 

隨着$target=9$total應該是10和$計數應該是5,但我越來越$total=9$count=9作爲似乎計數鍵,而不是值碼。同樣,如果目標是12,那麼$total應該是16.5,而$count應該是7,但我得到12和12.

希望這一切都有道理。如果有人可以編輯此代碼,以便它適用於任何數字和任何目標的數組,將不勝感激。

$count=0; 
$target=9; 
$total=0; 
foreach($numbers as $key => $value){ 
while($total < $target) { 
$total = $total+$value; 
$count++; 
} 
} 
echo "total is $total and count is $count"; 
+0

'$ outgoing'是什麼?爲什麼你的'foreach'裏面有'while'? –

+0

可能你想使用'$ target'而不是'$ outgoing'編輯錯誤 –

+0

說出$ target而不是$ outgoing – user1961653

回答

-1

if語句

$total = 0; 
foreach($numbers as $key => $value) 
{ 
    $total = $total+$value; 
    if($total >= $target) 
    { 
     $count = $key+1; 
     break; 
    } 
} 

添加而你並不需要while循環。

+1

你需要在某處增加'$ total'或者它將保持在0。 –

+1

完全匹配是no良好和$總需要增加 – user1961653

+0

是啊,這是隻是如果聲明的例子,但多數民衆贊成在這一點上,我會加上這個代碼 – Syeth

0

重命名$傳出至$目標和變化,同時對是否

$count=0; 
$target=9; 
$total=0; 
foreach($numbers as $key => $value){ 
    if($total < $target) { 
     $total = $total+$value; 
     $count++; 
    } 
    else 
    { 
     break; 
    } 
} 
echo "total is $total and count is $count"; 

UPD:重寫了代碼以避免與休息未使用循環條目

+0

感謝「如果」作品 – user1961653

+0

也想提到,在這種情況下,解決方案將數組鍵獨立,只要數組值爲 – GodlyHedgehog

+0

已更新的答案。 – GodlyHedgehog

2
$target = 9; 
$total = 0; 

foreach($numbers as $key => $value) { 
    if ($total >= $target) { 
     break; 
    } 

    $total += $value; 
} 

echo "total is $total and count is $key"; 
+0

感謝「if」作品 – user1961653

+0

可能要添加一些解釋或某種文字。 – AbraCadaver

0

你可以把你的支票$key如果key等於並大於$target break foreach循環。像這樣的東西 -

<?php 

$numbers = Array (0 => 1, 1 => 1, 2 => 1, 3 => 1, 4 => 6, 5 => 1, 6 => 5.5, 7 => 1, 8 => 1, 9 => 1, 10 => 1, 11 => 1, 12 => 1, 13 => 11); 

$count=0; 
$target=9; 
$total=0; 

foreach($numbers as $key => $value) { 
    if ($key >= $target) { 
    break; 
    } 
    $total += $value; 
    $count++; 
} 

echo "total is $total and count is $count"; 
?> 

希望得到你想要的結果。 (Y)。