Skip to content
Advertisement

Sum array values

I’m making a shipping service app to Shopify and my callback URL have this JSON post using json_decode to make an array. The value I want to sum is grams and putting into variable and then compare with the value of another variable using if ($weight <= $maxweight).

{
   "rate": {
       "items": [
           {
               "name": "My Product 3",
               "sku": null,
               "quantity": 1,
               "grams": 1000,
               "price": 2000,
               "vendor": "TestVendor",
               "requires_shipping": true,
               "taxable": true,
               "fulfillment_service": "manual"
           },
           {
               "name": "My Product 1",
               "sku": null,
               "quantity": 1,
               "grams": 500,
               "price": 1000,
               "vendor": "TestVendor",
               "requires_shipping": true,
               "taxable": true,
               "fulfillment_service": "manual"
           },
           {
               "name": "My Product 2",
               "sku": null,
               "quantity": 1,
               "grams": 2000,
               "price": 3000,
               "vendor": "TestVendor",
               "requires_shipping": true,
               "taxable": true,
               "fulfillment_service": "manual"
           }
       ],
       "currency": "CAD"
   }
}

Advertisement

Answer

You just need a simple foreach then under the loop, just add the value. Consider this example:

$total_weight = 0;
$json_string = '{ "rate":{ "items":[ { "name":"My Product 3", "sku":null, "quantity":1, "grams":1000, "price":2000, "vendor":"TestVendor", "requires_shipping":true, "taxable":true, "fulfillment_service":"manual" }, { "name":"My Product 1", "sku":null, "quantity":1, "grams":500, "price":1000, "vendor":"TestVendor", "requires_shipping":true, "taxable":true, "fulfillment_service":"manual" }, { "name":"My Product 2", "sku":null, "quantity":1, "grams":2000, "price":3000, "vendor":"TestVendor", "requires_shipping":true, "taxable":true, "fulfillment_service":"manual" } ], "currency":"CAD" }}';
$json_data = json_decode($json_string, true);

$max_weight = 10000;
foreach($json_data['rate']['items'] as $key => $value)  {
    $total_weight += $value['grams'];
}

echo $total_weight; // 3500
// then just compare whatever $max_weight value has to $total_weight
// rest of your desired code
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement