Array operations

array_operations

Sometimes we need to calculate the seller-wise shipping in eCommerce applications. Here I am giving the array operation which reduce your efforts of calculating seller-wise shipping using array operations.

Question:

How to get following output?
$cart = [
["sid"=>11, "shipping"=>40],
["sid"=>12, "shipping"=>50],
["sid"=>11, "shipping"=>15]
];

Required Output:

["11"=>55, "12"=>50]

Answer:

<?php

$cart = [
  ["sid"=>11, "shipping"=>40],
  ["sid"=>12, "shipping"=>50],
  ["sid"=>11, "shipping"=>15]
];

$output = [];

foreach($cart as $records)
{
  if(in_array($records["sid"], array_keys($output)))
  {
    $output[$records["sid"]] = $output[$records["sid"]] + $records["shipping"];
  }
  else
  {
    $output[$records["sid"]] = $records["shipping"];
  }
}

print_r($output);
?>

[Image Source : Google]