Skip to content

Instantly share code, notes, and snippets.

@devmsh
Last active June 11, 2017 14:52
Show Gist options
  • Save devmsh/1d0dbca853e8abcdcaa5b09c265522b3 to your computer and use it in GitHub Desktop.
Save devmsh/1d0dbca853e8abcdcaa5b09c265522b3 to your computer and use it in GitHub Desktop.
<?php
/**
* Group cart items by category, and calculate the total of each category ;)
**/
$cart = [
[ "name" => "product A", "price" => 15, "qty" => 5, "category" => "category 1"],
[ "name" => "product B", "price" => 20, "qty" => 4, "category" => "category 2"],
[ "name" => "product C", "price" => 30, "qty" => 2, "category" => "category 1"],
];
$cartByCategory = [];
foreach($cart as $item){
$category = $item['category'];
if(!isset($cartByCategory[$category])){
$cartByCategory[$category] = ["total" => 0,"items" => []];
}
$cartByCategory[$category]["total"] += $item['price'] * $item['qty'];
$cartByCategory[$category]["items"][]= $item;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment