phparraysaveragearray-column

Get average of single column in a 2d array


I have an array with the following structure:

[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"

I try to make an average of every 5th entry

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

Except for the first part (where it is presented the legend of the array) and last part

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

Where is presented the total. The code I am using is:

$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);

But i get the error: undefined offset [5]. Any ideas why? 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" }`

Solution

  • 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