Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
合并Php数组_Php_Arrays - Fatal编程技术网

合并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);
}