我对 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/