求和多维数组列

时间:2017-10-30 11:36:33

标签: php arrays columnsorting

我必须总结一些多维数组的列,并且我在它上面停留了3天。我的阵列是这样的:

$items = [ 
   0 => [
     0 => [
       'category' => 'CATEGORY ONE',
       'goal' => 12,
       'reached' => '14',
       'points' => '148',
    ],
    1 => [
      'category' => 'CATEGORY TWO',
      'goal' => 12,
      'reached' => '14',
      'points' => '148',
    ]
   ],
   1 => [
     0 => [
       'category' => 'CATEGORY ONE',
       'goal' => 12,
       'reached' => '14',
       'points' => '148',
    ],
    1 => [
      'category' => 'CATEGORY TWO',
      'goal' => 12,
      'reached' => '14',
      'points' => '148',
    ]
   ]
];

我无法解析这些数据以获得每个类别的值的总和,因此它必须像这样返回:

$items = [
 0 => [
   'category' => 'CATEGORY ONE',
   'goal' => 24,
   'reached' => '48',
   'points' => '296',
],
1 => [
  'category' => 'CATEGORY TWO',
  'goal' => 12,
  'reached' => '14',
  'points' => '296',
]];

2 个答案:

答案 0 :(得分:1)

这不是通用代码,只是做你想要的

$result = [];
$categoriesData = [];
// aggregate data by category name
foreach ($items as $item) {
    foreach ($item as $category) {
        $categoryName = $category['category'];
        if (!isset($categoriesData[$categoryName])) {
            $categoriesData[$categoryName] = [
                'goal' => 0,
                'reached' => 0,
                'points' => 0
            ];
        }
        foreach ($category as $key => $value) {
            if ($key === 'category') continue;
            $categoriesData[$categoryName][$key] += (int) $value;
        }
    }
}

// result data
foreach ($categoriesData as $key => $value) {
    $result[] = [
        'category' => $key,
        'goal' => (string) $value['goal'],
        'reached' => (string) $value['reached'],
        'points' => (string) $value['points']
    ];
}

答案 1 :(得分:1)

试试这个:

$itemsFlattened = call_user_func_array('array_merge', $items);

$itemsSummed = [];
foreach ($itemsFlattened as $item) {
    if (array_key_exists($item['category'], $itemsSummed)) {
        $itemsSummed[$item['category']]['goal'] += $item['goal'];
        $itemsSummed[$item['category']]['reached'] += $item['reached'];
        $itemsSummed[$item['category']]['points'] += $item['points'];
    } else {
        $itemsSummed[$item['category']] = $item;
    }
}
$itemsSummed = array_values($itemsSummed);

print_r($itemsSummed);

输出:

Array
(
    [0] => Array
        (
            [category] => CATEGORY ONE
            [goal] => 24
            [reached] => 28
            [points] => 296
        )

    [1] => Array
        (
            [category] => CATEGORY TWO
            [goal] => 24
            [reached] => 28
            [points] => 296
        )

)