Last active
June 11, 2017 14:52
-
-
Save devmsh/1d0dbca853e8abcdcaa5b09c265522b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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