PHP - 不同级别的Sum数组

时间:2014-02-25 18:52:41

标签: php arrays

有一个像这样的阵列:

Array
(
0 =>
   array (
      'Country' => 'USA'
      'State' => 'California'
      'City' => 'Los Angeles'
      'qty'    => '200'
   )
1 =>
   array (
      'Country' => 'USA'
      'State' => 'California'
      'City' => 'San Diego'
      'qty'  => '50'
   )
2=>
  array (
      'Country' => 'USA'
      'State' => 'New York'
      'City' => 'Albany'
      'qty' => '100'
  )
)

我正在尝试使用上面的总计输出每个分组的数据:

USA                  350
   California        250
      Los Angeles    200
      San Diego       50
   New York          100
      Albany         100

到目前为止,我使用过这种方法:how to group result in subgroups in php

我希望将子项总数高于子项并添加更多级别。我通过重复循环来获得级别,但是在我到达最后一个孩子之前,如何让总计显示在同一行(孩子们之上)?

1 个答案:

答案 0 :(得分:1)

您可以使用array_reduce函数来聚合平面数组,即:

$data = array(
0 =>
   array (
      'Country' => 'USA',
      'State' => 'California',
      'City' => 'Los Angeles',
      'qty'    => '200'
   ),
1 =>
   array (
      'Country' => 'USA',
      'State' => 'California',
      'City' => 'San Diego',
      'qty'  => '50'
   ),
2=>
  array (
      'Country' => 'USA',
      'State' => 'New York',
      'City' => 'Albany',
      'qty' => '100'
  )
);

$result = array();

$result = array_reduce(
  $data,
  function($result, $element) {
    $prefix = '';
    foreach (array('Country', 'State', 'City') as $key) {
      if (!isset($result[$element[$key]])) {
        $result[$prefix.$element[$key]] = $element['qty'];
      } else {
        $result[$prefix.$element[$key]] += $element['qty'];
      }
      $prefix .= '  ';
    }
    return $result;
  },
  $result
);


print_r($result);

结果是:

Array
(
    [USA] => 350
    [  California] => 50
    [    Los Angeles] => 200
    [    San Diego] => 50
    [  New York] => 100
    [    Albany] => 100
)