2013-03-01 91 views
1

我需要從數組中的子數組中總結一些值。按鍵總結數組值

我有這樣的陣列

Array 
(
    [smecid_2] => Array 
     (
      [0] => 1 
      [1] => SMEC 55.6 
      [2] => 960 
      [3] => 864 
      [4] => 960 
      [5] => 864 
     ) 

    [smecid_6] => Array 
     (
      [0] => 3 
      [1] => SMEC 55.6 ATEX EX 
      [2] => 1290 
      [3] => 1161 
      [4] => 3870 
      [5] => 3483 
     ) 

) 

我想要做的是從總結各個領域的關鍵[4]每個子陣列並能夠總迴響在$總量;

在這個例子中$total;將是4830(960 + 3870)。

此外,當用戶提交更多產品進行訂購時,該陣列可以容納更多的子陣列,然後是這2個。

回答

1
<?php 
$array = array 
(
    'smecid_2' => array 
     (
      0 => 1, 
      1 => 'SMEC 55.6', 
      2 => 960, 
      3 => 864, 
      4 => 960, 
      5 => 864, 
     ), 

    'smecid_6' => array 
     (
      0 => 3, 
      1 => 'SMEC 55.6 ATEX EX', 
      2 => 1290, 
      3 => 1161, 
      4 => 3870, 
      5 => 3483, 
     ) 

); 

$sum = 0; 
foreach ($array as $subarray) 
{ 
    $sum += $subarray[4]; 
} 
echo $sum; 

See it in action

+1

哇非常感謝爲快速幫助約翰!它像一個魅力:) – user2124412 2013-03-01 17:11:41