以不同格式迭代和求和一个级别的数组

问题描述

我现在有一个数据数组,它生成的格式几乎相同,但在每个级别我都有一个与之前的项目略有不同的总计索引。

我目前正在循环它,但每次迭代的“总”索引都存在问题,因为它具有更扁平的格式并且没有那么多级别。我在这里使用“Adam”作为示例,但想法是有多个人具有相同的完全格式化的数组,我想按类别总计,然后按部门总计(“01”和“04”,然后“Adam”、“Sam”等的总计。

我做错了什么?

代码

$data = array(
"Adam" => array (
"01" => array (
  "categories" => array(
    "CategoryOne"=> array(
      "downloads" => 10,"saves" => 2,"expected"=> array(
        "possible" => 30,),"CategoryTwo"=> array(
      "downloads" => 15,"saves" => 8,"expected"=> array(
        "possible" => 15,"total"=> array(     //this totals all categories
      "downloads" => 25,"saves" => 10,"expected"=> array(
        "possible" => 45,"total"=> array(     //this would total anything under "01" like "categories","items",etc.
    "downloads" => 25,"expected"=> array(
      "possible" => 45,"04" => array (
  "categories" => array(
    "CategoryOne"=> array(
      "downloads" => 10,"total"=> array(      //totals categories
      "downloads" => 25,"total"=> array(         //this would total anything under "04" like "categories","total"=> array(         //this would total "01" and "04".
  "downloads" => 50,"saves" => 20,"expected"=> array(
    "possible" => 90,"total"=> array(         //this would be a grand total for Adam 
  "downloads" => 50,)

);

$results = [];


foreach ($data as $i) {
    foreach ($i as $group => $n) {
        if (!array_key_exists($group,$results)) $results[$group] = [];
        foreach ($n as $category_name => $category) {
            if (!array_key_exists($category_name,$results[$group])) $results[$group][$category_name] = [];
            foreach ($category as $item_name => $item) {
                if (!array_key_exists($item_name,$results[$group][$category_name])) {
                    $results[$group][$category_name][$item_name] = $item;
                } else {
                    foreach ($item as $purpose => $dollars) {
                        $results[$group][$category_name][$item_name][$purpose] += $dollars;
                    }
                }
            }
        }
    }
};

dd($results);

期望的输出是相似的,但对于所有用户来说都是一样的,而不仅仅是亚当:

"01" => array (
  "categories" => array(
    "CategoryOne"=> array(
      "downloads" => 10,"total"=> array(         //this would be a grand total for all people in the array
  "downloads" => 50,

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)