Get averages of values from multidimensional array

2019-09-18 02:32发布

问题:

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
        )

)

回答1:

You could parse your input array into an array where the keys are the dates and the values are arrays of places for that date:

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

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

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

And now just go over that temporary array, calculate the averages and produce the output format you want:

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

print_r($averages);


回答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);

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)