最大的foreach数组值? [英] foreach max array value?

查看:326
本文介绍了最大的foreach数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的PHP和我有问题循环。我有一个foreach循环,

I'm fairly new to php and i have problem with loops. I have a foreach loop,

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

这给一些阵列,这取决于我有多少内容有。目前我有2个,

which gives some arrays, depending on how many contents i have. currently i have 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);
}

但我仍然不明白我也应该找出其中的数组是最高价。任何建议,将AP preciated

but i still dont get how i'm supposed to find out in which array is the max price. any suggestions would be appreciated

推荐答案

您应该存储密钥,以及让你可以在循环之后看它:

You should store the keys as well so that you can look it up after the loop:

$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];

请注意,如果有多个产品与同价位的结果将是不可靠的。

Note that the results will be unreliable if there are multiple products with the same price.

这篇关于最大的foreach数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆