Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中使用多维数组进行计算_Php - Fatal编程技术网

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

如何在php中使用多维数组进行计算,php,Php,我正在尝试使用多维数组进行计算。这是我的密码: <?php $items = array( array('id' =>1, 'DESC' =>'Widget Corporation', 'Price' =>30.00), array( 'id' =>2, 'DESC' =>'Website Corporation', 'Price' =>40.00,

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

<?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;
}
你得到的是“60 80 100 120”。每件商品的价格都翻了一番,全部加在一起,因为你没有办法把它分开。将代码更改为:

$total = 0;
foreach($items as $item){
    $total += $item['Price'];
    echo "$total<br />\n";
}
echo "$total<br />\n";
$total=0;
foreach($items作为$item){
$total+=$item['Price'];
回显“$total
\n”; } 回显“$total
\n”;
试试这个

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

替换为此代码

如果您想要的只是价格的总和,请尝试

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

你在你的数组中循环,每件物品都有自己的价格;然后,您回显结果(没有尾随的换行符)。你想产生什么?你甚至理解
foreach()
循环在做什么吗?在
foreach
主体周围省略
{}
是一种不好的做法。当我意识到大括号正在使我的代码在视觉上受到污染时,我倾向于(负责任地)忽略这个建议。我只是在重复的语句太长或存在多个语句块时加上它。@tassoevan提出不良做法是不好的,尽管我们个人的习惯和良好做法是社区成员和开发团队之间的协议。我所有的同事都这么做。
 $total=0; 
 foreach($items as $item){
     $total =$total + $item['Price'] ;    
 }
 echo $total;
$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;
$total = 0;
foreach ($items as $item){
 $total += $item['Price'];   
}    
echo $total;