通过电子邮件分组数据并汇总-symfony / php

时间:2016-05-08 08:35:53

标签: php arrays json

我从db获取数据并解析为array / json - 这就是我得到的结果(每个结果100行):

 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
)

我的问题是如何通过电子邮件(拥有相同电子邮件的客户)对客户进行分组,以及结果如下所示的有效方式。

“sum” - 每个电子邮件对象中的数组,包含一些数据的摘要(例如 - “total”,并且还采用具有最近日期的行的相同其他数据)

  $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),
    );

然后解析所有json。

1 个答案:

答案 0 :(得分:0)

首先创建一个新阵列并将客户插入其中:

operator+

然后,您可以使用array_map覆盖新的$customers = []; foreach ($data as $customer) { if (!isset($customers[$customer['customerEmail']])) { $customers[$customer['customerEmail']] = []; } array_push($customers[$customer['customerEmail']], $customer); } 数组,添加$customers字段或对每组客户应用任何其他过滤器:

sum

我希望这会把它搞清楚一点。