Php 在数组中显示min()值

Php 在数组中显示min()值,php,arrays,for-loop,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 &

我想在多维数组中显示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>";
    }                              
}                
$totalCustomer=count($customerArray);
$position=0;
foreach($customerArray作为$custom){
$position=$position+1;
如果($totalCustomer-$position<9){
$top[]=$custom['spend'];
$maxprice=max($top);
echo“最高消费价格为“$maxprice”。
”; } }
我会使用
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);

@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 );

这是我的,你能解释一下你做了什么吗。对我来说似乎太快了。如果我想显示业务的横截面或任何其他数组,该怎么办?基本上,您的代码都有问题,很难解释。我添加了一些注释来解释我在做什么。注意,如果你不理解某些东西,你可能需要表现出更多的努力,特别是如果你是新手的话。您是否阅读了
usort()
array\u slice()
array\u reverse()
的手册页?如果不是,你应该从这里开始。我运行了你的代码,但是它给了我很多错误,比如usort()期望参数1是数组,null给定的数组_slice()期望参数1是数组,null给定的等等。你需要声明
$array
或者改用
$customerArray
。“这不是很明显吗?”呵呵,我想是的。这就是为什么我说这是我的进步。也可以基于相同的阵列进行横截面吗?基本上我喜欢你的想法。你有没有试过这是更快,还是你认为它更快?@Paulocoghi你能解释一下代码吗。我没有看到代码的输出。它的空白。@ HEK2MGL,我尝试过这种方法,只是在C++中,而且总是更快,因为它不进行比较。我很想看看它在PHP中的表现,而且,由于PHP数组实现(也比任何其他比较方法都快),它可能会在O(n)而不是O(0)中运行。哦,忘了提到这一点,您可以使用
Array\u map()
Array\u reduce()
替换foreach循环。我想这会更快。你应该试试,当然!
array\u map()
array\u reduce()
都提供了O(n)复杂度,有助于加快解决方案的速度:)非常感谢!