2017-10-30 3 views
0

i多次元配列のいくつかの列を合計しなければならず、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', 
    ] 
    ] 
]; 

私はそれがこのように返すために持っているので、各カテゴリの値の合計を取得するには、このデータを解析するために何abbleませんでした:

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

誰もが私は私を助けることができます`これにこだわった。

+0

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

出力を計算された? –

+3

間違いを見つけて修正して正しい結果を得るためにコードを投稿してください。 – Pascal

答えて

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

欲しいものはこの試しください: `=> '48 'に達し' はどのように

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

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

) 
+0

tksだ!あなたは私の生命を救った! –

+0

@RichardFeliciano問題はありません:)私の答えがあなたを助けたら、[それを受け入れる]ことを忘れないでください(https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) –