c.k
c.k

Reputation: 1105

Displaying unique values in loop

I have in my database a table of product requests.

Datas

I am now making a summary of user's request. Which displays all the user's request without duplicating the product names (should be unique), and get the total quantity and amount.

This is my code and what I have tried so far. I tried using unique array.

$all_product_name = array();

foreach ( $rows as $row ) {

    $all_product_name[] = $row;
    $allproduct = array_unique( $all_product_name );
}

 foreach ($allproduct as $product) { 

    print_r($product);

 }

This gives me all the products and not the unique product names.

What I would like to do is to is to show only unique product names, and the sum of the quantity and amount of all products.

enter image description here

I am stuck, any help and ideas?

Upvotes: 0

Views: 96

Answers (1)

Shuchi Sethi
Shuchi Sethi

Reputation: 803

Solution 1: Use a query, like in mysql it would be - select sum(prod_quantity), sum(prod_amount) group by prod_name

Solution 2: Iterate over the rows to create associative array of prod_name

foreach($rows as $row) {
    $prod_name = $row['prod_name'];
    $prod[$prod_name]['amount'] = $prod[$prod_name]['amount'] + $row['prod_amount'];
    $prod[$prod_name]['quantity'] = $prod[$prod_name]['quantity'] + $row['prod_quantity'];
}

Output will be like:

Array
(
    [Product1] => Array
    (
        [amount] => 2600 //sum of prod_amount
        [quantity] => 6  //sum of prod_quantity
    )

[Product2] => Array
    (
        [amount] => 6600
        [quantity] => 5
    )
)

Upvotes: 1

Related Questions