在数组

时间:2015-05-04 14:58:52

标签: php arrays for-loop

我想在多维数组中显示10个最高数字和10个最低数字。
我已经找到了使用max()显示最大数字的方法,但是当我使用min()时,最少的值会一次又一次地循环10次,例如2.

如何重用我的代码以在数组中显示最小值?

  $totalCustomer = count($customerArray);
$postion = 0;
foreach ($customerArray as $custom) {
    $postion = $postion + 1;
    if($totalCustomer - $postion < 9){
        $top[] = $custom['spend'];
        $maxprice = max($top);

        echo "Max spend price is ". $maxprice. "<br>";
    }                              
}                

2 个答案:

答案 0 :(得分:1)

我会使用usort

/* Sort the array the value of 'spend' */
usort($customerArray, function($a, $b) {
    if($a['spend'] == $b['spend']) {
        return 0;
    } else if ($a['spend'] > $b['spend']) {
        return -1;
    } else {
        return 1;
    }
});

/* The top 10 elements are now on top of the array */    
$top = array_slice($customerArray, 0, 10);

/* If we reverse the array using array_reverse() the 
   smallest items are on top */
$low = array_slice(array_reverse($customerArray), 0, 10);

答案 1 :(得分:1)

@ hek2mgl答案很好。但是你可以利用PHP数组的索引来避免排序和获得性能。

$prices = [];

foreach ( $customerArray as $custom )
{
    // This approach uses your price as an ordering index, and supposes two decimal points
    $index = intval( $custom['spend'] * 100 );
    $prices[$index] = $custom['spend'];
}


// Showing lowest 10 prices
$top = array_slice( $prices, 0, 10 );

// Showing top 10 prices
$low = array_slice( array_reverse( $prices ), 0, 10 );