数组合并:使用foreach?

Array merge: use foreach?

我有 2 个数组:

$im=explode(",", $data['products']);
$imi=explode(",", $data['period']);

相关的:

$data['products'] = balon,globo,sesta
$data['period'] = 1,1,2

所以当我合并结果时它是:

Array ( [0] => DS Basic [1] => DS Pro [2] => DS Start [3] => 1 [4] => 1 [5] => 2 )

问题是我需要这样关联它:

DS Basic = 1 , DS Pro = 1 , DS Start = 2

我正在使用 array_merge($im,$imi)

如何使用 foreach 执行此操作? 我想要这个:

Array ( [0] => DS Basic [1] => DS Pro [2] => DS Start)
Array ( [0] => 1 [1] => 1 [2] => 2 )

所以当我使用它时它可以像

using foreach

DS basic has a period of 1

DS pro has a period of 1

DS start has a period of 2

您可以修复合并结果如下:

$merged = array_merge($im,$imi);
$period = array();
// Loop through the merged items
foreach ($merged as $k=>$v) {
  // Check if the value is an integer
  if ((int)$v) {
    // Move this value to the period array
    $period[] = $v;
    // Remove it from the merged array
    unset($merged[$k]);
  }
}
// Reindex the merged array to revalue the keys
$merged = array_values($merged);
// Test the output
echo '<h1>Merged Array:</h1>';
echo '<pre>';
echo print_r($merged);
echo '</pre>';
echo '<h1>Excess Array:</h1>';
echo '<pre>';
echo print_r($period);
echo '</pre>';
exit;
$merged = array();
if (count($im) != count($imi)) {
    print "custom merging is not possible...";
}
else {
    for($i=0 ; $i<count($im) ; $i++) {
        $merged[$im[$i]] = $imi[$i];
    }
}

你可以做foreach

    $newArr = [];
    foreach($im $key => $val)
    {
        $newArr[] = [$val[0] => $imi[$key][0], $val[1] => $imi[$key][1], $val[2] => $imi[$key][2]];
    }
    print_r($newArr);

或合并:

  $result = array_combine($im, $imi);

你需要的是组合而不是合并 ;) 看看php在[=10上的手册=].

请不要考虑您想要的结果将一组数据作为键(在您的示例中来自 products 数组的值),您不应该有重复的值,否则您会丢失它们