-1

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

<?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

4

6 回答 6

3
$total = 0;
foreach($items as $item){
    $total += $item['Price'];
}
echo $total;
于 2013-05-07T13:36:07.247 回答
1

你得到的是“60 80 100 120”。每件商品的价格翻了一番,全部卷在一起,因为您无法将其分开。将您的代码更改为:

$total = 0;
foreach($items as $item){
    $total += $item['Price'];
    echo "$total<br />\n";
}
echo "$total<br />\n";
于 2013-05-07T13:36:12.027 回答
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;

用此代码替换

于 2013-05-07T13:38:20.400 回答
0

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

$total = 0;
foreach ($items as $item){
 $total += $item['Price'];   
}    
echo $total;
于 2013-05-07T13:39:18.230 回答
0
$total = 0;

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

echo $total;
于 2013-05-07T13:36:32.750 回答
0

尝试这个

 $total=0; 
 foreach($items as $item){
     $total =$total + $item['Price'] ;    
 }
 echo $total;
于 2013-05-07T13:37:50.910 回答