2017-10-19 108 views
0

我從URL獲取總銷售物品,並返回包含'SKU','Date','Quantity'和'Total Price'的數組。 我想計算相同'SKU'的總數量並存儲在新陣列中。 任何人都可以告訴我如何在PHP語言中做到這一點?陣列與相同SKU的總和值

$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

什麼 你有沒有嘗試過?請添加該代碼 –

+0

任何嘗試呢?你嘗試過一個foreach()嗎? – Andreas

+0

http://php.net/manual/en/function.array-column.php http://php.net/manual/en/function.array-map.php – Osama

回答

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." "; 
} 
+0

我試過這個,但什麼都沒有發生。 –

+0

它的工作在我的最後,請確認你正在唱正確的變量名 –

+0

我有更新的問題,還包括代碼。你能再讀一遍嗎? –

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; 
} 
+0

我也試過這個,但沒有得到正確的輸出 –

+0

關於你最新的問題更新,你必須在第一個foreach循環中重命名變量: 'foreach($ datr ['SoldItems'] as $ sale)''' –

+0

謝謝你提供的解決方案也在工作! –