dongxu1029 2014-05-17 15:09
浏览 59
已采纳

foreach max array value?

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

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

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] => ზედა
)

my goal is to save the array which has the max price in it as a different variable. I'm kinda stuck on how to do that, i managed to find the max price with the max() function like so

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

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

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

  • 写回答

3条回答 默认 最新

  • dpy3846 2014-05-17 15:21
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了