Get averages of values from multidimensional array where date key's match?

拜拜、爱过 提交于 2019-12-12 02:26:58

问题


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)


来源:https://stackoverflow.com/questions/18853327/get-averages-of-values-from-multidimensional-array-where-date-keys-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!