1

我想弄清楚如何从这个数组中的某些键(呼叫、联系人和音调)中获取平均值。我希望结果是一个数组,其中只有这三个键,其中包含三个键的平均值。所以应该是 [calls]=>27 [contacts]=>13 等。在此先感谢。

Array ( 
    [0] => Array ( 
              [index] => 78 
              [name] => RepOne 
              [repnumber] => 0001 
              [date] => 2013-03-16 07:17:14 
              [calls] => 36 
              [contacts] => 21 
              [pitches] => 10 
    ) 

    [1] => Array ( 
              [index] => 75 
              [name] => RepOne 
              [repnumber] => 0001 
              [date] => 2013-03-13 10:03:06 
              [calls] => 18 
              [contacts] => 12 
              [pitches] => 8  
    ) 

    [2] => Array ( 
              [index] => 74 
              [name] => RepOne 
              [repnumber] => 0001 
              [date] => 2013-03-12 03:03:06 
              [calls] => 20 
              [contacts] => 6 
              [pitches] => 3 
    ) 
)
4

7 回答 7

2

以下代码假定您的数据的结构类似于以下 JSON:

[
    { 'call': 5, 'contacts': 2, 'pitches': 3 },
    { 'call': 22, 'contacts': 17, 'pitches': 1 }
]

或者像这样的 JSON:

{
    'rep1_id': { 'call': 5, 'contacts': 2, 'pitches': 3 },
    'rep2_id': { 'call': 22, 'contacts': 17, 'pitches': 1 }
}

试试这个:

function array_average_by_key( $arr )
{
    $sums = array();
    $counts = array();
    foreach( $arr as $k => &$v )
    {
        foreach( $v as $sub_k => $sub_v )
        {
            if( !array_key_exists( $sub_k, $counts ) )
            {
                $counts[$sub_k] = 0;
                $sums[$sub_k]   = 0;
            }
            $counts[$sub_k]++;
            $sums[$sub_k]  += $sub_v;
        }
    }
    $avg = array();
    foreach( $sums as $k => $v )
    {
        $avg[$k] = $v / $counts[$k];
    }
    return $avg;
}
于 2013-03-19T17:09:05.813 回答
2
$avrage = array('calls' => 0,'contacts' => 0,'pitches' => 0); #prevent notice  
$i = count($yourArray);  #UPDATE
foreach($yourArray as $value)
{
   $avrage['calls'] += $value['calls'];
   $avrage['contacts'] += $value['contacts'];
   $avrage['pitches'] += $value['pitches'];
}
# UPDATE : check zero value before using division .
$avrage['calls'] = ($avrage['calls']?floor($avrage['calls']/$i):0);   #round value
$avrage['contacts'] = ($avrage['contacts']?floor($avrage['calls']/$i):0);
$avrage['pitches'] = ($avrage['pitches']?floor($avrage['calls']/$i):0); 
于 2013-03-19T17:15:13.943 回答
0
<?php

$dataRows = ...your array...;

$averages = array('calls' => 0, 'pitches' => 0, 'contacts' => 0)

//sum average for each row
foreach($dataRows as $row) {
    foreach($row as $key => $value) {
        $add = false;

        //only add for specific values
        switch($key) {
            case 'calls':
            case 'pitches':
            case 'contacts':
                $add = true;
        }

        if($add) {
            $averages[$key] += $value;
        }

    }
}

//divide by number of rows for average
//the &$value is important as it is the refernce to the value
//so it will set the value in the array
foreach($average as &$value) {
    $value /= count($dataRows);
}
于 2013-03-19T17:12:11.487 回答
0

我猜你的意思是这样的。我正在为“平均值”取平均值。

<?php
$newAverages = array();

$contacts = '';
$pitches = '';
$calls = '';

//Simply add them all together
foreach ($original_array as $key=>$throwaway){
 $contacts = $contacts + $original_array[$key]['contacts'];
 $pitches = $pitches + $original_array[$key]['pitches'];
 $calls = $calls + $original_array[$key]['calls'];
}

$totalReps = count($original_array);

//Then divide by the total
$newAverages['contacts'] = $contacts/$totalReps;
$newAverages['pitches'] = $pitches/$totalReps;
$newAverages['calls'] = $calls/$totalReps;

print_r($newAverages);
?>
于 2013-03-19T17:14:57.407 回答
0

尽管 php 中存在一些像 array_sum() 这样的快捷函数,但对于这种二维结构,直接一步一步的解决方案可能是最好的:

$input_array = ...
$wanted_columns = array ("call", "contacts", "pitches");
$result = array_fill_keys ($wanted_columns, 0);

foreach ($input_array as $row) 
    foreach ($wanted_columns as $column_name) 
        $result[$column_name] += $row[$column_name];

$array_size = count ($input_array);
foreach ($result as &$value)
    $value /= $array_size;

** 上面的代码适用于任何一组想要的列,您只需在 $wanted_columns 处设置

于 2013-03-19T17:24:37.533 回答
0

这是另一种更详细的方法:

// a function to extract values by particular column names
function array_columns( array $array, array $columns )
{
    $result = array_fill_keys( $columns, array() );
    foreach( $array as $value )
    {
        foreach( $columns as $column )
        {
            $result[ $column ][] = is_array( $value ) && array_key_exists( $column, $value )
                                   ? $value[ $column ]
                                   : null;
        }
    }

    return $result;
}

// a function to calculate the average value of array elements
function array_average( array $array )
{
    $count = count( $array );
    return $count > 0 ? array_sum( $array ) / $count : 0;
}

用法:

$averages = array_map( 'array_average', array_columns( $yourArray, array( 'calls', 'contacts', 'pitches' ) ) );

var_dump( $averages );

产生:

array(3) {
  ["calls"]=>
  float(24.666666666667)
  ["contacts"]=>
  int(13)
  ["pitches"]=>
  int(7)
}
于 2013-03-19T18:11:49.083 回答
0

如果您使用的是 PHP 5+,则可以使用以下内容:

function calculateAverage($array){
    $sum = array_sum($array);
    $average = $sum / count($array);

    return $average;
}

// Assuming the original array above is used
$contactsAverage = calculateAverage(array_column($associativeArrayAbove, "contacts") );
echo $contactsAverage;
于 2015-02-20T22:06:36.803 回答