我从网址获取所售商品总数,然后返回包含' SKU','日期'数量'和总价格#39; 我想计算相同的总数量' SKU'并存储在新数组中。 任何人都可以告诉我如何用PHP语言做到这一点?
$url ="abc";
<pre>
$post_fields = array();
$post_fields['EndDateUtc']=$end;
$post_fields['StartDateUtc']=$start;
$post_fields['TenantToken']=$TenantToken;
$post_fields['UserToken']= $UserToken;
$data_string = json_encode($post_fields);
</pre>
<pre>
$curl_header = array();
$curl_header[] = 'Content-type: application/json';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 180);
curl_setopt($ch, CURLOPT_TIMEOUT, 180);
$output = curl_exec($ch);
curl_close($ch);
$datr = json_decode($output, TRUE);
print_r($datr);
数组输出: --------------
Array
(
[SoldItems] => Array
(
[0] => Array
(
[SKU] => 8273-Navy-M
[Date] => 2017-10-12
[Quantity] => 15
[TotalPrice] => 7685
)
[1] => Array
(
[SKU] => 2879-S-B-White-3XL
[Date] => 2017-10-12
[Quantity] => 2
[TotalPrice] => 298
)
[2] => Array
(
[SKU] => 8273-Navy-M
[Date] => 2017-10-12
[Quantity] => 2
[TotalPrice] => 298
)
[3] => Array
(
[SKU] => 2262-S-A-Black-2XL
[Date] => 2017-10-12
[Quantity] => 1
[TotalPrice] => 199
)
)
)
</pre>
thank you so much.
答案 0 :(得分:1)
请试试这个:
$skuTotal = [];
foreach($items['SoldItems'] as $item) {
if(isset($skuTotal[$item['SKU']])){
$skuTotal[$item['SKU']] += $item['Quantity'];
}else{
$skuTotal[$item['SKU']] = $item['Quantity'];
}
}
foreach($skuTotal as $sku => $total) {
echo "SKU " . $sku . " , Total " . $total." ";
}
答案 1 :(得分:0)
您应该使用类似的东西,它未经测试,可能需要进行一些调整以符合您的实际情况:
$totalsBySku = [];
foreach($soldItems as $sale) {
$totalsBySku[$sale['SKU']] += $sale['Quantity'];
}
foreach($totalsBySku as $sku => $total) {
print "SKU " . $sku . " has a total quantity of " . $total;
}