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.
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.
P.S. 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.