合并Php数组
我有两个阵列:合并Php数组,php,arrays,Php,Arrays,我有两个阵列: $codes = array ( 0 => 'SW10055', 1 => 'SW10050', 2 => 'SW10050' ); $quantities = array ( 0 => '2', 1 => '4', 2 => '3' ); 第一个数组的每个值都对应于位于相同位置的第二个数组中的值 因此,“SW10055”对应于“2”,第一个“SW10050”对应于“4”,第一个数组“SW10050”的最后一个元
$codes = array (
0 => 'SW10055',
1 => 'SW10050',
2 => 'SW10050'
);
$quantities = array (
0 => '2',
1 => '4',
2 => '3'
);
第一个数组的每个值都对应于位于相同位置的第二个数组中的值
因此,“SW10055”对应于“2”,第一个“SW10050”对应于“4”,第一个数组“SW10050”的最后一个元素对应于“3”
我需要创建如下数组:
$result = array(
'SW10055' => 2,
'SW10050' => 7,
);
其中,键是代码,值是相对数量(在代码相同的地方添加)
最好的方法是什么?
谢谢 这里我们首先使用
array\u combine
获取键和值,然后在数组上迭代求和值
输出:
Array
(
[SW10055] => 2
[SW10050] => 7
)
只需在数组上循环并从中创建一个新数组
$result = [];
foreach ($codes as $i => $code) {
if (isset($result[$code])) {
$result[$code] += $quantities[$i];
} else {
$result[$code] = $quantities[$i];
}
}
@ewcz联合收割机不是他想要的-请注意重复的indizies
$result = [];
foreach ($codes as $i => $code) {
if (isset($result[$code])) {
$result[$code] += $quantities[$i];
} else {
$result[$code] = $quantities[$i];
}
}
$arrResult = array ();
foreach ($arrCodes as $intIndex => $strCode)
{
$arrResult[$strCode] = $quantities[$intIndex] + intval(isset($arrResult[$strCode]) ? $arrResult[$strCode] : 0);
}