Home > front end >  Group multi dimensional array according to title field and display the sum of all the rows with the
Group multi dimensional array according to title field and display the sum of all the rows with the

Time:06-28

I have this multi dimensional array of sales transactions, that I get from an API, so no database access. Some transactions have the same product as another transaction:

array (
  0 => 
  array (
    'id' => 1,
    'product_title' => 'Product 1',
    'selling_price' => 50.0,
    'quantity' => 1,
  ),
  1 => 
  array (
    'id' => 2,
    'product_title' => 'Product 2',
    'selling_price' => 80.0,
    'quantity' => 2,
  ),
  2 => 
  array (
    'id' => 3,
    'product_title' => 'Product 1',
    'selling_price' => 50.0,
    'quantity' => 8,
  ),
  3 => 
  array (
    'id' => 4,
    'product_title' => 'Product 4',
    'selling_price' => 120.0,
    'quantity' => 3,
  ),
  4 => 
  array (
    'id' => 5,
    'product_title' => 'Product 2',
    'selling_price' => 80.0,
    'quantity' => 3,
  ),
)

I need to display the items according to title and then the products with the highest revenue (quantity * selling_price) displayed descending order.

I've got this and then I get just the title of each product:

$results = array();
foreach ($sales as $key => $value) {
    $results[$value['product_title']] = $value[0];
}
echo "<table>";
foreach ($results as $key => $value) {
    echo "<tr><td>" . $key . "</td></tr>";
};
echo "</table>";

But I want the title and the revenue(quantity * selling_price) with the product with the highest revenue at the top.

CodePudding user response:

A solution with php7 and more, with:

$input = array (
  0 => 
  array (
    'id' => 1,
    'product_title' => 'Product 1',
    'selling_price' => 50.0,
    'quantity' => 1,
  ),
  1 => 
  array (
    'id' => 2,
    'product_title' => 'Product 2',
    'selling_price' => 80.0,
    'quantity' => 2,
  ),
  2 => 
  array (
    'id' => 3,
    'product_title' => 'Product 1',
    'selling_price' => 50.0,
    'quantity' => 8,
  ),
  3 => 
  array (
    'id' => 4,
    'product_title' => 'Product 4',
    'selling_price' => 120.0,
    'quantity' => 3,
  ),
  4 => 
  array (
    'id' => 5,
    'product_title' => 'Product 2',
    'selling_price' => 80.0,
    'quantity' => 3,
  ),
);

Group and sum:

foreach($input as $row){
  $sum[$row['product_title']] ??= 0;
  $sum[$row['product_title']]  = $row['selling_price']*$row['quantity'];
}

And finaly DESC ordering:

arsort($sum);
//var_export($sum);
foreach($sum as $key => $value) {
    echo $key .' / '.$value . PHP_EOL ;
}

Results:

Product 1 / 450
Product 2 / 400
Product 4 / 360
  •  Tags:  
  • php
  • Related