php求二维数组某一列总和

来自:互联网
时间:2023-05-07
阅读:

在PHP开发过程中,我们常常需要对数组中的数据进行求和操作。针对一维数组,我们可以使用array_sum函数直接求和,但是当数组变成了二维数组,我们就需要一些额外的操作来求得指定列的总和。

例如,我们现在有一个存储销售数据的二维数组,每个子数组代表一个商品的销售数据,包括商品id、销售量、单价等信息。我们需要求得所有商品的总收入,即销售量与单价的乘积的总和。

那么,该如何实现这一操作呢?

首先,我们可以使用array_column函数来获取指定列的数组。这个函数是PHP5.5+版本新增的,其语法为:array_column ( array $input , mixed $column_key [, mixed $index_key = null ] ) ,其中,$input为要提取列的数组,$column_key为要提取的列的键名或数字索引,$index_key可选,为要作为返回数组的key的列的键名或数字索引。

例如,在上述的销售数据二维数组中,我们可以使用如下代码获取所有商品的销售量数组:

$sold_amount = array_column($sales_data, 'sold_amount');

接下来,我们可以使用array_reduce函数对$sold_amount数组进行累加操作,从而得到销售量的总和。其语法为:array_reduce ( array $array , callable $callback [, mixed $initial = null ] ),其中,$array为要进行累加操作的数组,$callback为自定义的回调函数,$initial为初始值。

例如,我们可以使用如下代码求得所有商品销售量的总和:

$total_sold_amount = array_reduce($sold_amount, function($carry, $item){
    return $carry + $item;
});

接下来,我们需要对单价数组进行同样的操作,从而得到所有商品单价的总和。最后,我们可以将两个总和相乘,得到所有商品的总收入。

完整的代码如下:

$sales_data = array(
    array('id' => 1, 'sold_amount' => 50, 'unit_price' => 2.5),
    array('id' => 2, 'sold_amount' => 20, 'unit_price' => 3.2),
    array('id' => 3, 'sold_amount' => 100, 'unit_price' => 1.8),
);

$sold_amount = array_column($sales_data, 'sold_amount');
$total_sold_amount = array_reduce($sold_amount, function($carry, $item){
    return $carry + $item;
});

$unit_price = array_column($sales_data, 'unit_price');
$total_unit_price = array_reduce($unit_price, function($carry, $item){
    return $carry + $item;
});

$total_revenue = $total_sold_amount * $total_unit_price;

echo '所有商品的总收入为:' . $total_revenue;

以上代码执行后输出:所有商品的总收入为:630。

综上所述,当我们需要对二维数组的某一列进行求和操作时,可以使用array_column函数获取指定列的数组,再使用array_reduce函数对数组进行累加操作,从而得到该列的总和。通过这些方法,我们可以更加方便地对数据进行处理,提高开发效率。

返回顶部
顶部