foreach max array value?

时间:2014-05-17 15:09:47

标签: php arrays max

我对php很新,我遇到循环问题。我有一个foreach循环,

foreach ($contents as $g => $f)
{
  p($f);
}

给出一些数组,具体取决于我有多少内容。目前我有2,

Array
(
    [quantity] => 1
    [discount] => 1
    [discount_id] => 0
    [id] => 1506
    [cat_id] => 160
    [price] => 89
    [title] => კაბა
)

Array
(
    [quantity] => 1
    [discount] => 1
    [discount_id] => 0
    [id] => 1561
    [cat_id] => 160
    [price] => 79
    [title] => ზედა
)

我的目标是将具有最高价格的数组保存为另一个变量。我有点坚持如何做到这一点,我设法用max()功能找到最高价格

foreach ($contents as $g => $f)
{

    $priceprod[] = $f['price'];
    $maxprice = max($priceprod);
   p($maxprice);
}

但我仍然不知道我应该如何找出哪个数组是最高价格。任何建议将不胜感激

3 个答案:

答案 0 :(得分:3)

您也应该存储密钥,以便在循环后查找:

$priceprod = array();

foreach ($contents as $g => $f)
{
  // use the key $g in the $priceprod array
  $priceprod[$g] = $f['price'];
}

// get the highest price
$maxprice = max($priceprod);

// find the key of the product with the highest price
$product_key = array_search($maxprice, $priceprod);

$product_with_highest_price = $contents[$product_key];

请注意,如果有多个产品具有相同的价格,结果将不可靠。

答案 1 :(得分:1)

检查循环外部数组的最大函数。

foreach ($contents as $g => $f)
{

    $priceprod[] = $f['price'];

}
$maxprice = max($priceprod);
p($maxprice);

答案 2 :(得分:0)

在这里,您可以使用单循环解决方案处理具有相同最高价格的多个项目。

$maxPrice = - INF;
$keys = [];
foreach($contents as $k=>$v){
    if($v['price']>$maxPrice){
        $maxPrice = $v['price'];
        $keys = [$k];
    }else if($v['price']==$maxPrice){
        $keys[] = $k;
    }
}