微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

我目前正在循环它,但每次迭代的“总”索引都存在问题,因为它具有更扁平的格式并且没有那么多级别。我在这里使用“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 举报,一经查实,本站将立刻删除。