简体   繁体   English

多维数组中值的加法

[英]Addition of values in multi-dimensional array

I have the following array: 我有以下数组:

array:3 [▼
  0 => array:2 [▼
    "modId" => "3"
    "prdWt" => 1500.0
  ]
  1 => array:2 [▼
    "modId" => "8"
    "prdWt" => 50.0
  ]
  2 => array:2 [▼
    "modId" => "8"
    "prdWt" => 10.0
  ]
]

What I am trying to achieve is that, the child array should add up the values of prdWt if the modId is same. 我想要实现的是,如果modId相同,则子数组应该将prdWt的值prdWt

What I want is: 我想要的是:

array:2 [▼
  0 => array:2 [▼
    "modId" => "3"
    "prdWt" => 1500.0
  ]
  1 => array:2 [▼
    "modId" => "8"
    "prdWt" => 60.0
  ]
]

Code so far that I have tried: 到目前为止,我已经尝试过的代码:

//$prdModWt is the parent array coming from session
foreach ($prdModWt as $prd) {
    $val = $this->checkKey($prdModWt, 'modId', $prd['modId']);

    var_dump($val);

    $a[] = $this->sum_index($prdModWt, 'prdWt');
}

public function sum_index($arr, $col_name)
{
    $sum = 0;
    foreach ($arr as $item) {
        $sum += $item[$col_name];
    }
    return $sum;
}

public function checkKey($array, $key, $val)
{
    foreach ($array as $item) {
        if (isset($item[$key]) && $item[$key] == $val) {
            return true;
        }
    }
    return false;
}

I know that this is way too simple to achieve, but I am failing in this. 我知道这太简单了,但是我做不到。 So kindly help me out. 所以请帮我。

PS The parent array is dynamic.. Meaning the values are coming from the session only but the values are stored in the session after fetching it from the database. PS父数组是动态的。。这意味着这些值仅来自会话,但是在从数据库中获取值之后,这些值将存储在会话中。

You can simply achieve that within single loop only like as 您可以简单地在单个循环中实现,就像

$arr = [["modId" => "3",
    "prdWt" => 1500.0
  ],["modId" => "8",
    "prdWt" => 50.0
  ],["modId" => "8",
    "prdWt" => 10.0
  ]
];

$result = [];
foreach($arr as $key => $value){
    $hash = $value['modId'];
    if(isset($result[$hash])){
        $result[$hash]['prdWt'] += $value['prdWt'];
    }else{
        $result[$hash]['modId'] = $value['modId'];
        $result[$hash]['prdWt'] = $value['prdWt'];
    }
}
print_r(array_values($result));

Demo 演示版

Well, an easy way to do this (but ugly, I'll try to come up with something easier) is the following: 好吧,一个简单的方法可以做到这一点(但丑陋的,我会尝试一些简单的方法):

$results = [];
foreach($array as $i => $item) {
    if($item['modId'] == $array[$i + 1]['modId']) {
        $results[] = ['modId' => $item['modId'], 'prdWt' => $item['prdWt'] + $array[$i + 1]['prdWt']];
    }
}

You could also easily write a recursive solution I believe 我相信您也可以轻松编写一个递归解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM