php - foreach 最大数组值?

标签 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);
}

但我仍然不明白我应该如何找出哪个数组中的最高价格。任何建议将不胜感激

最佳答案

您还应该存储 key ,以便可以在循环后查找它:

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

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

关于php - foreach 最大数组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23712864/

相关文章:

php - 使用 cURL 通过 javascript 抓取网站

javascript - 按键将对象分组为二维数组

arrays - 类型为 [SuperClass] 且元素类型为 [Subclass] 的 Swift 数组

T-SQL:选择最小值和最大值的每个实例

mysql - 从mysql表中获取年、月、周、日、小时数据的最大值

php - 重构 PHP 类

php - 如何在opencart中创建全局函数

C# IEnumerable<string> 和 string[]

c++ - 我如何修改此函数,以便如果函数的参数是特定结构,它会返回具有更大整数的结构?

php - 使网络服务器成为双方之间的中继