Jump to content

New Help With an Array


vincej

Recommended Posts

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 !

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/249873-new-help-with-an-array/
Share on other sites

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.