I getting data from db and parsing to array/json - this what I getting (100 rows per result):
array[1] = (
"CustomerId" => 1,
"CustomerEmail" =>iii@gmail.com,
"CustomerName" =>name1,
"date" => "10-10-16",
"total" =>3
),
array[2] = (
"CustomerId" => 2,
"CustomerEmail" =>iii@gmail.com,
"CustomerName" =>name2,
"date" => "9-10-16",
"total" =>2
)
array[3] = (
"CustomerId" => 3,
"CustomerEmail" =>anotherEmail@gmail.com,
"CustomerName" =>name3,
"date" => "18-10-16",
"total" =>54
)
My question is how can I group by email (customers that have the same email) the customers and what is the efficient way that the result will be like below.
"sum"- array in each email object that include a summarise of some data (for instance - "total" , and also take the same other data of the row that have the recent date)
$customers['iii@gmail.com'] = array(
'c1' => array('name' => 'name1', 'id' => '1' ,"date"=>"10-10-16","total"=3"),
'c2' => array('name' => 'name2', 'id' => '2',"date"=>"09-10-16","total"=>2),
'sum' => array('name' => '2', 'id' => '1',"date"=>"date"=>"10-10-16","total"=>5),
);
$customers['anotherEmail@gmail.com] = array(
'c3' => array('name' => 'name', 'id' => '12',"date"=>"date"=>"18-10-16","total"=>54),
'sum' => array('name' => '1', 'id' => '12',"date"=>"date"=>"18-10-16","total"=>54),
);
and then parse all to json.
Start by creating a new array and inserting customers into it:
$customers = [];
foreach ($data as $customer) {
if (!isset($customers[$customer['customerEmail']])) {
$customers[$customer['customerEmail']] = [];
}
array_push($customers[$customer['customerEmail']], $customer);
}
Then you can use array_map to go over the new $customers
array, add the sum
fields or apply any other filters to every group of customers:
$result = array_map(
// Runs for each element of $customers
function ($customersGroup) {
// create your sum object
$sum = ...
// Insert the `sum` into $customersGroup
$customersGroup['sum'] = $sum;
// Return the modified $customersGroup
return $customersGroup;
},
$customers
);
I hope this clears it up a little.