找到关联数组php中的最大值

时间:2016-12-10 12:55:22

标签: php arrays associative-array

我想在关联数组中找到最大的和。我有2年的信息,我找到了每年的总和,现在我想找到哪一个更大,这个数额属于哪一年。

<?php
    $year = array (
    "Year 2015 " =>  array( 
        "Televizor " => "3",
        "Lavatrice"     => "4",
        "Kompjuter"     => "5",
        "printer"     => "5",
    ),
    "Year 2016 " =>  array( 
        "Televizor " => "3",
        "lavatrice"     => "7",
        "kompjuter"     => "4",
        "printer"     => "1",
    )
    );

    foreach($year as $key => $product){
        echo "<br>";
        echo "$key";
        echo"<table border=1 cellspacing=0>
            <tr>
            <td>Produkti</td>
            <td>Sasia</td>
            </tr>";
        echo "<br>";

        foreach( $product as $key => $value){
            echo "<tr>
                <td>$key</td>
                <td>$value</td>
                </tr>";
        }

        echo "</table>";
    }

    foreach($year as $key => $product){
        echo"$key";

        $arrayOfValues=array_values($product);
        $arraySum=array_sum($arrayOfValues);

        $avg=$arraySum/count($arrayOfValues);
        echo "Average=$avg";
        echo " ";

        $maxValueArray=array();
        array_push($maxValueArray, $arraySum);
        echo "Sum=$maxValueArray[0]";
        echo "<br>";
    }
?>

这是输出:

Year 2015 
Produkti    Sasia
Televizor   3
Lavatrice   4
Kompjuter   5
printer 5

Year 2016 
Produkti    Sasia
Televizor   3
lavatrice   7
kompjuter   4
printer 1
Year 2015 Average=4.25 Sum=17
year 2016 Average=3.75 Sum=15

我想打印“2015年度最大金额= 17”

2 个答案:

答案 0 :(得分:0)

要做到这一点,您只需要创建一个带有估值的数组。

$yearSumValues = array_map('array_sum', $year);

$max = max($yearSumValues);
$maxYearKey = array_search($max, $yearSumValues);

echo 'Max sum is: ', $max, '<br />';
echo 'Data key is: ', $maxYearKey, '<br />';

if( !is_null($maxYearKey) ) {
    echo 'Values are: ', var_dump($year[$maxYearKey]);
}

所以,现在,在$max,你将拥有最大的价值。所以,$maxYearKey包含了最大年份的关键(小心均衡)。

var_dump($year[$maxYearKey]);

  Produkti    Sasia
  Televizor   3
  Lavatrice   4
  Kompjuter   5
  printer 5

精简版

$yearSumValues = array_map('array_sum', $year);
if( ($maxYearKey = array_search(max($yearSumValues), $yearSumValues)) != null ) {
    echo 'found ', $maxYearKey, ' with values ', var_dump($year[$maxYearKey]);
}
  

你可以玩:http://phplab.io/lab/IgJkR

答案 1 :(得分:0)

使用array_reducearray_sumarray_search函数的简短解决方案:

$result = array_reduce($year, function ($prev, $item) {
    return (array_sum($prev) > array_sum($item))? $prev : $item;
}, []);

print_r(array_search($result, $year) ." has the biggest sum = ". array_sum($result));

输出:

Year 2015  has the biggest sum = 17

http://php.net/manual/en/function.array-reduce.php