Reputation: 728
sele_itmid =
Array
(
[0] => 1
[1] => 1
[2] => 5
[3] => 6
)
$recp_qty =
Array
(
[0] => 4
[1] => 16
[2] => 1
[3] => 10
)
//when i tried using
$comine = array_combine($sele_itmid,$recp_qty);
print_r($comine);exit();
am getting a result like
Array
(
[1] => 16
[5] => 1
[6] => 10
)
what i actually want is
[1]=>4
[1] => 16
[5] => 1
[6] => 10
If possible some one Please explain why array_combine neglecting it!!
after getting an array what i actually want need to sum values of same keys
Upvotes: 1
Views: 48
Reputation: 92854
"why array_combine neglecting it?" - an array doesn't allow duplicate keys.
Here is a simple solution using array_map
function (it will sum up the values of the same keys):
$result = [];
array_map(function($key, $b) use (&$result){
(isset($result[$key]))? $result[$key] += $b : $result[$key] = $b;
}, $sele_itmid, $recp_qty);
print_r($result);
The output:
Array
(
[1] => 20
[5] => 1
[6] => 10
)
Upvotes: 1
Reputation: 2777
In here $sele_itmid 's values are used as the key of $comine array. Since an array can not have duplicate keys first value is rejected.
Upvotes: 0
Reputation: 311843
Sounds as though you'd want to just map the two arrays together:
function sum($v1, $v2) {
return $v1 + $v2;
}
$result = array_map('sum', $sele_itmid, $recp_qty);
Upvotes: 0