在这里,我试图获取卖方的收入,但是问题是我无法将重复的数组值分组为一个。
逻辑功能。
function getMonthlyIncomeOfSellerById($sellerId)
{
$data = array();
$ddd = array();
$query = "SELECT date_format(created_at,'%M'), product_id,sell_discount,SUM(sell_quantity) FROM sellers_sells WHERE seller_id=? AND YEAR(created_at) = YEAR(CURRENT_DATE()) GROUP BY date_format(created_at,'%M'),seller_id,product_id ORDER BY created_at";
$stmt = $this->con->prepare($query);
$stmt->bind_param('s',$sellerId);
$stmt->execute();
$stmt->bind_result($monthName,$productId,$sellDiscount,$sellQuantity);
while ($stmt->fetch())
{
$d['monthName'] = $monthName;
$d['productId'] = $productId;
$d['sellDiscount'] = $sellDiscount;
$d['sellQuantity'] = $sellQuantity;
array_push($data, $d);
}
$stmt->close();
$netProfit = 0;
$maxProfit = 0;
foreach ($data as $dt)
{
$product = $this->getProductById($dt['productId']);
$product['productPrice'] = ($product['productPrice']/100)*$dt['sellDiscount'];
if ($product['productName']==='FAROOQUI MASSAGE OIL' && $product['productBrand']==='FHC' && $product['productSize']==='50ML')
{
$maxPrice = $product['productPrice']*$dt['sellQuantity'];
$price = ($product['productPrice']-10)*$dt['sellQuantity'];
}
else if ($product['productName']==='FAROOQUI MASSAGE OIL' && $product['productBrand']==='FHC' && $product['productSize']==='100ML')
{
$maxPrice = $product['productPrice']*$dt['sellQuantity'];
$price = ($product['productPrice']-15)*$dt['sellQuantity'];
}
else if ($product['productName']==='FAROOQUI MASSAGE OIL' && $product['productBrand']==='FHC' && $product['productSize']==='200ML')
{
$maxPrice = $product['productPrice']*$dt['sellQuantity'];
$price = ($product['productPrice']-30)*$dt['sellQuantity'];
}
$netProfit = $netProfit+$price;
$maxProfit = $maxProfit+$maxPrice;
$dts['monthName'] = $dt['monthName'];
$dts['netProfit'] = $netProfit;
$dts['maxProfit'] = $maxProfit;
array_push($ddd, $dts);
}
print_r($ddd);
}
用重复的值来输出。
Array
(
[0] => Array
(
[monthName] => January
[netProfit] => 2050
[maxProfit] => 2800
)
[1] => Array
(
[monthName] => March
[netProfit] => 2214
[maxProfit] => 3024
)
[2] => Array
(
[monthName] => March
[netProfit] => 4149
[maxProfit] => 5604
)
[3] => Array
(
[monthName] => March
[netProfit] => 4523
[maxProfit] => 6148
)
)
但是在这里,我想将其与月份分组,然后将所有值加到一个。
像这样。
Array
(
[0] => Array
(
[monthName] => January
[netProfit] => 2050
[maxProfit] => 2800
)
[1] => Array
(
[monthName] => March
[netProfit] => 10886
[maxProfit] => 14776
)
)
我怎样才能做到这一点?
谢谢
您可以通过使用monthName
as键来按“月”分组。如果密钥不存在,请使用默认值创建一个新条目。然后,您可以+
从数据中添加()当前值。
$monthName = $dt['monthName'];
if (!isset($ddd[$monthName])) {
$ddd[$monthName] = [
'monthName' => $monthName,
'netProfit' => 0,
'maxProfit' => 0,
];
}
$ddd[$monthName]['netProfit'] += $netProfit;
$ddd[$monthName]['maxProfit'] += $maxProfit;
代替
$dts['monthName'] = $dt['monthName'];
$dts['netProfit'] = $netProfit;
$dts['maxProfit'] = $maxProfit;
array_push($ddd, $dts);
要删除添加的密钥,可以使用:
$ddd = array_values($ddd);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句