php 获取二维数组中单个列的平均值

ozxc1zmp  于 2023-01-04  发布在  PHP
关注(0)|答案(1)|浏览(135)

我有一个具有以下结构的数组:

[1]=>
    [1]=>
  array(13) {
    [0]=>
    string(8) "Avg. CPC"
    [1]=>
    string(6) "Budget"
    [2]=>
    string(13) "Budget period"
    [3]=>
    string(3) "CTR"
    [4]=>
    string(11) "Campaign ID"
    [5]=>
    string(6) "Clicks"
    [6]=>
    string(10) "Conv. rate"
    [7]=>
    string(4) "Cost"
    [8]=>
    string(12) "Cost / conv."
    [9]=>
    string(3) "Day"
    [10]=>
    string(11) "Impressions"
    [11]=>
    string(7) "Network"
    [12]=>
    string(17) "Total conv. value"
  }
  [2]=>
  array(13) {
    [0]=>
    string(7) "3675556"
    [1]=>
    string(8) "40000000"
    [2]=>
    string(3) "day"
    [3]=>
    string(6) "17.65%"
    [4]=>
    string(9) "405105304"
    [5]=>
    string(1) "9"
    [6]=>
    string(5) "0.00%"
    [7]=>
    string(8) "33080000"
    [8]=>
    string(1) "0"
    [9]=>
    string(10) "2016-05-07"
    [10]=>
    string(2) "51"
    [11]=>
    string(14) "Search Network"
    [12]=>
    string(3) "0.0"
  }
  .
  .
  .
  .
  [32]=>
    array(13) {
    [0]=>
    string(5) "Total"
    [1]=>
    string(8) "40000000"
    [2]=>
    string(2) "--"
    [3]=>
    string(5) "7.15%"
    [4]=>
    string(2) "--"
    [5]=>
    string(3) "194"
    [6]=>
    string(5) "0.00%"
    [7]=>
    string(9) "639390000"
    [8]=>
    string(1) "0"
    [9]=>
    string(2) "--"
    [10]=>
    string(4) "2713"
    [11]=>
    string(2) "--"
    [12]=>
    string(3) "0.0"

我尝试平均每5个条目

[5]=>
        string(1) "9"

除了第一部分(显示数组图例的地方)和最后一部分

[32]=>
        array(13) {
        [0]=>
        string(5) "Total"

其中显示了总数。我使用的代码是:

$sum = 0;
$pathClicks = $data->data[1];
foreach($pathClicks as $key => $item){
   if($key > 1)   {
      $arrayClicks[] = [$item[5]];
      $sum += $item[5];
   }
} 
$avgClicks = ($sum / count($arrayClicks)); 
var_dump($avgClicks);

但我得到的错误:未定义的偏移量[5]。知道为什么吗?var_dump for $item:

array(13) { `
[0]=> string(7) "3452000" 
[1]=> string(8) "40000000" 
[2]=> string(3) "day" 
[3]=> string(6) "13.70%" 
[4]=> string(9) "405105304" 
[5]=> string(2) "10" 
[6]=> string(5) "0.00%" 
[7]=> string(8) "34520000" 
[8]=> string(1) "0" 
[9]=> string(10) "2016-06-29" 
[10]=> string(2) "73" 
[11]=> string(14) "Search Network" 
[12]=> string(3) "0.0" }`
u59ebvdq

u59ebvdq1#

array_column

$arr= $pathClicks;
array_shift($arr);  //removes the first part of array
array_pop($arr);    //removes the last  part of array
$percents = array_column($arr, 5);

foreach($percents as $percent)
    $arr[] = str_replace('%', '', $percent);

$sum = array_sum($arr);  //calculates the sum of all key=5 in array
$avgClicks = $sum / count(array_column($arr, 5));  //avg

相关问题