从日期键匹配的多维数组中获取平均值?

时间:2013-09-17 15:02:03

标签: php arrays for-loop foreach average

我有以下多维数组

Array
(
    [0] => Array
        (
            [place] => 1
            [date] => 2013-01-01
        )

    [1] => Array
        (
            [place] => 2
            [date] => 2013-01-02
        )

    [2] => Array
        (
            [place] => 3
            [date] => 2013-01-03
        )

    [3] => Array
        (
            [place] => 10
            [date] => 2013-01-01
        )

    [4] => Array
        (
            [place] => 8
            [date] => 2013-01-02
        )

    [5] => Array
        (
            [place] => 5
            [date] => 2013-01-03
        )

)

如何获得日期匹配的每个数组的平均位置,因此输出数组看起来像?我能做的最多就是循环遍历数组,提取日期非常简单,但找到匹配并获得平均值超出了我。提前谢谢。

Array
(
    [0] => Array
        (
            [place] => 5.5
            [date] => 2013-01-01
        )

    [1] => Array
        (
            [place] => 5
            [date] => 2013-01-02
        )

    [2] => Array
        (
            [place] => 6.5
            [date] => 2013-01-03
        )

)

2 个答案:

答案 0 :(得分:2)

$input = array(
    array('place' => 1, 'date' => '2013-01-01'),
    array('place' => 2, 'date' => '2013-01-02'),
    array('place' => 3, 'date' => '2013-01-01'),
);
foreach($input as $pair) $tmp[$pair['date']][] = $pair['place'];
foreach($tmp as $key => $value){
    $result[] = array('place' => array_sum($value) / count($value), 'date' => $key);
}
//var_dump($result);

结果:

array (size=2)
  0 => 
    array (size=2)
      'place' => int 2
      'date' => string '2013-01-01' (length=10)
  1 => 
    array (size=2)
      'place' => int 2
      'date' => string '2013-01-02' (length=10)

答案 1 :(得分:1)

您可以将输入数组解析为一个数组,其中键是日期,值是该日期的地点数组:

$tmp = array();
foreach( $input as $entry  ) {
    $date = $entry["date"];

    if( !array_key_exists( $date, $tmp ) ) {
        $tmp[$date] = array();
    }

    $tmp[$date][] = $entry["place"];
}

现在只需查看临时数组,计算平均值并生成所需的输出格式:

$averages = array();
foreach( $tmp as $date => $places ) {
    $sum = array_sum($places);
    $averages[] = array(
        "date" => $date,
        "place" => $sum / count($places)
    );
}

print_r($averages);