PHP Snippet 1:
$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
PHP Snippet 2:
// Convert the raw json to an array with json_encode & the 'true' option.
$json_array = json_decode($raw_json, true);
// Now use array_map to return and array of just the value of grams.
$grams_array = array_map(function ($item) { return intval($item['grams']); }, $json_array['rate']['items'] );
// Echo the sum of the grams array with by using array sum.
echo array_sum($grams_array);
PHP Snippet 3:
// Set the raw JSON.
$raw_json = <<<EOT
{
"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"
}
}
EOT;
// Convert the raw json to an array with json_encode & the 'true' option.
$json_array = json_decode($raw_json, true);
// Now use array_map to return and array of just the value of grams.
$grams_array = array_map(function ($item) { return intval($item['grams']); }, $json_array['rate']['items'] );
// Echo the sum of the grams array with by using array sum.
echo array_sum($grams_array);
PHP Snippet 4:
var_export(
array_sum(
array_column(
$array['rate']['items'],
'grams'
)
)
);