vincej Posted October 26, 2011 Share Posted October 26, 2011 Hi - I am struggling with summing the total values of a multi dimensional array. Each sub-array contains the same type of information ie 'Order Number', 'Product' 'Quantity', 'Price'. Therefore the array could easily have the same order number multiple times but contain different products. See illustration below. My challenge is I need to extract all the common order numbers and then sum into a grand total the cost of that order. Array( Array ( order_number: 123 product: shirt quantity: 2 price: 20 ) Array ( order_number: 123 product: Tie quantity: 1 price: 20 ) ) I have gone though all the available PHP array functions and have not found one which would do the job. I have also though of doing it in SQL as well as all this data is in a DB. I'm pulling my hair out and struggling - MANY THANKS to all how can help ! Quote Link to comment Share on other sites More sharing options...
jotorres1 Posted October 26, 2011 Share Posted October 26, 2011 I didn't read the full post but just by looking at the array, it's wrong PHP <?php $item = array( array ( 'order_number' => 123, 'product' => 'shirt', 'quantity' => 2, 'price' => 20 ) array ( 'order_number' =>123, 'product' => 'Tie ', 'quantity' => 1, 'price' =>20 ) ) $total = 0; foreach($item as $key){ $total += $key['price']; } echo $total; ?> I'm kinda in a hurry, but something like this should help. Quote Link to comment Share on other sites More sharing options...
Psycho Posted October 26, 2011 Share Posted October 26, 2011 If the data is in a database, then you definitely want to go that route. You don't state what you DB structure is, but I would think you should have one table to hold the basic order info and then an associative table to hold the order details (i.e. the line items). But, you also don't state how you are going to use this value. If you are going to query the DB for the complete order details to display on the page, then you can just calculate the total as you process the line items. However, if you just need a process to display just the order info (not the line items) along with a total, then you should do that with a query using SUM() and GROUP BY. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.