Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.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中使用quantity键对数组求和?_Php_Arrays - Fatal编程技术网

如何在PHP中使用quantity键对数组求和?

如何在PHP中使用quantity键对数组求和?,php,arrays,Php,Arrays,我有这个阵列: array(2) { [0]=> array(5) { ["id"]=> string(1) "1" ["name"]=> string(5) "Test1" ["weight"]=> string(3) "5.0" ["price"]=>

我有这个阵列:

array(2) {
  [0]=>
  array(5) {
    ["id"]=>
    string(1) "1"
    ["name"]=>
    string(5) "Test1"
    ["weight"]=>
    string(3) "5.0"
    ["price"]=>
    string(1) "7"
    ["quantity"]=>
    string(1) "2"
  }
  [1]=>
  array(5) {
    ["id"]=>
    string(1) "2"
    ["name"]=>
    string(5) "Test2"
    ["weight"]=>
    string(3) "7.0"
    ["price"]=>
    string(2) "11"
    ["quantity"]=>
    string(1) "1"
  }
}
我可以把价格加起来:

echo array_sum(array_column($items, 'price'));
但我无法计算数量超过1的项目。如何在PHP中正确总结这一点

编辑:我的代码的问题,不清楚的是它没有考虑数量超过1的项目。这个总数应该是25。我用的密码是18

echo array_reduce(
    $items, 
    function($total, $item) {
        $total += $item['price'] * $item['quantity'];

        return $total;
    }, 
    0
);
或者一个简单的foreach

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

您可以使用数组\u walk功能

$total = 0;
array_walk( $arr, function ( $item ) use ( &$total )
{
$total += $item['price'] * $item['quantity'];
});
echo $total;

对不起,我不明白这个问题。你所展示的代码和我所说的一样,所以也许你可以解释一下它的输出,然后解释它有什么问题。它没有考虑数量超过1的项目,哦,但那是因为PHP并不神奇。您没有编写任何代码来考虑数量,所以它甚至没有尝试是的,这是我在数组中添加数量之前使用的代码,我如何做到这一点?这两种方法都有好处吗?