0

I have the following multidimensional array,

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
        )

)

How can I get the average place each array where the dates match, so the out put array would look like? The most i've been able to do is loop over the arrays extracting the dates which is pretty easy but finding matches and getting the averages is beyond me. Thanks in advance.

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
        )

)
4

2 回答 2

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)
于 2013-09-17T15:23:07.277 回答
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);
于 2013-09-17T15:19:11.433 回答