如何用php中的多维数组进行计算

时间:2013-05-07 13:33:41

标签: php

我正在尝试使用多维数组进行计算。这是我的代码:

<?php
$items = array(
    array('id' =>1,
        'DESC' =>'Widget Corporation',
        'Price' =>30.00),
    array(
        'id' =>2,
        'DESC' =>'Website Corporation',
        'Price' =>40.00,
    ),
    array(
        'id' =>3,
        'DESC' =>'Content Management',
        'Price' =>50.00,
    ),
    array(
        'id' =>4,
        'DESC' =>'Registration System',
        'more'=>'Please Buy it',
        'Price' =>60.00
    )
);

foreach($items as $item){
    $total =$item['Price'] + $item['Price'];
    echo $total;
}

我得到的结果是:6080100120而不是180

6 个答案:

答案 0 :(得分:3)

$total = 0;
foreach($items as $item){
    $total += $item['Price'];
}
echo $total;

答案 1 :(得分:1)

你得到的是“60 80 100 120”。每个项目的价格翻了一倍,全部汇总在一起,因为你没有办法将它分开。将您的代码更改为:

$total = 0;
foreach($items as $item){
    $total += $item['Price'];
    echo "$total<br />\n";
}
echo "$total<br />\n";

答案 2 :(得分:1)

$items = array(
    array('id' =>1,
        'DESC' =>'Widget Corporation',
        'Price' =>30.00),
    array(
        'id' =>2,
        'DESC' =>'Website Corporation',
        'Price' =>40.00,
    ),
    array(
        'id' =>3,
        'DESC' =>'Content Management',
        'Price' =>50.00,
    ),
    array(
        'id' =>4,
        'DESC' =>'Registration System',
        'more'=>'Please Buy it',
        'Price' =>60.00
    )
);

foreach($items as $item){
    $total+=$item['Price'] ;

}
echo $total;

替换为此代码

答案 3 :(得分:0)

$total = 0;

foreach ( $items as $item )
    $total += $item['Price'];

echo $total;

答案 4 :(得分:0)

试试这个

 $total=0; 
 foreach($items as $item){
     $total =$total + $item['Price'] ;    
 }
 echo $total;

答案 5 :(得分:0)

我想要的只是价格的总和,试试

$total = 0;
foreach ($items as $item){
 $total += $item['Price'];   
}    
echo $total;