我是相当新的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);
}
,但我仍然不知道我应该如何找出在哪个数组是最大的价格。如有任何建议,不胜感激
还应该存储键,以便在循环后查找:
$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];
请注意,如果有多个产品具有相同的价格,则结果将不可靠。
检查循环外数组的max函数
foreach ($contents as $g => $f)
{
$priceprod[] = $f['price'];
}
$maxprice = max($priceprod);
p($maxprice);
这里你得到了一个单循环解决方案,处理多个具有相同最大价格的项目。
$maxPrice = - INF;
$keys = [];
foreach($contents as $k=>$v){
if($v['price']>$maxPrice){
$maxPrice = $v['price'];
$keys = [$k];
}else if($v['price']==$maxPrice){
$keys[] = $k;
}
}