找到数组php中的最小值和最大值

时间:2018-01-25 05:29:54

标签: php arrays max minimum array-reduce

Array
(
    [0] => Array
        (
            [package] => LTE_15AGB
            [value] => Array
                (
                    [0] => 52690
                    [1] => 24700
                    [2] => 43972
                    [3] => 506417
                    [4] => 488125
                    [5] => 935918
                    [6] => 1322816
                    [7] => 1189040
                    [8] => 2805279
                    [9] => 2764825
                    [10] => 1688294
                    [11] => 1228812
                    [12] => 2232345
                    [13] => 3356143
                    [14] => 1193213
                    [15] => 167589
                    [16] => 1373104
                    [17] => 691411
                    [18] => 1398647
                    [19] => 5
                )

        )

    [1] => Array
        (
            [package] => LTE_15AGB_NT
            [value] => Array
                (
                    [0] => 953370
                    [1] => 151168
                    [2] => 37605
                    [3] => 428769
                    [4] => 755222
                    [5] => 1146719
                    [6] => 494289
                    [7] => 889002
                    [8] => 307200
                    [9] => 127972
                    [10] => 2764815
                    [11] => 1426224
                    [12] => 262669
                    [13] => 648757
                    [14] => 1485
                    [15] => 1202
                    [16] => 998
                    [17] => 1
                )

        )

)

这就是我的尝试:

$tmp = array();
foreach($arrayName as $arg){ 
    $tmp[$arg['package']][] = $arg['value']; 
}

$output = array();
foreach($tmp as $type => $labels){
    $output[] = array( 'package' => $type, 'value' => $labels, ); 
}

print_r(($output))

3 个答案:

答案 0 :(得分:2)

试试这个:

foreach ($your_array as $subarr) {
    echo $subarr[package]." minimum = ";
    echo min($subarr[value])." and maximum = ";
    echo max($subarr[value])."<br>";
 }

这将输出每个包名以及最小值和最大值。

答案 1 :(得分:1)

@Arebhy Sri,你应该在php中搜索数组,这就像基本问题一样。

$finalArray = [];    
foreach ($mainArr as  $subArr){
        $array = $subArr['value'];
        sort($array);

        $tempArray['minimum'] = reset($array);
        $tempArray['maximum'] = end($array);
        $tempArray['package'] = $subArr['package'];
        $finalArray[] = $tempArray;
    }



$finalArray //you can use

我使用简单的foreach和数组reset()end()的两个函数。

  

reset():返回第一个数组元素的值,如果数组为空则返回FALSE。

     

end():返回最后一个元素的值,或返回空数组的FALSE。

答案 2 :(得分:1)

只需使用min()max()功能。

您的代码

foreach(array_column($array, 'value') as $key => $values){
    echo PHP_EOL . 'SubArray '. $key .' min = '. min($values) . ' and max value = '.  max($values);
}

输出

  

SubArray 0 min = 5且max value = 3356143
  SubArray 1 min = 1且max value = 2764815

参考文献:

现场演示: https://eval.in/941702