0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.