通过从PHP中提取一个键,以特定的方式合并两个数组


Merge 2 arrays in PHP in a specific way by taking one key from each

正在努力寻找以特定方式合并2个阵列的逻辑,例如我有

array('lemons', 'oranges', 'grapes', 'pineapples');

array('carrots', 'onions', 'cabbage');

我想以结束

array('lemons', 'carrots', 'oranges', 'onions', 'grapes', 'cabbage' 'pineapples');

即从各个方面将它们合并为一个整体,而不仅仅是在结束和开始时将它们合并在一起。

$x = 0;
while ($x < max(count($fruit), count($veg))) {
  if (isset($fruit[$x])) {
    $merged[] = $fruit[$x];
  }
  if (isset($veg[$x])) {
    $merged[] = $veg[$x];
  }
  $x++;
}

像那样的东西?

不是最复杂的答案,但这就是我所想到的。

$array1 = array('lemons', 'oranges', 'grapes', 'pineapples');
$array2 = array('carrots', 'onions', 'cabbage');
$iterator = 0;
// Continue until the end of both arrays
while (!empty($array1) || !empty($array2)) {
    // If iterator is odd then we want the second array, or if array one is empty
    if ($iterator++ % 2 == 1 && !empty($array2) || empty($array1)) {
        $array3[] = array_shift($array2);
    } else {
        $array3[] = array_shift($array1);
    }
}
var_dump($array3);

输出:

array('lemons', 'carrots', 'oranges', 'onions', 'grapes', 'cabbage' 'pineapples');

循环索引(从0到max(count($array1),count($array2)),然后在循环语句中,如果设置了索引,则将每个数组的索引元素附加到一个新元素。

试试这样的东西:

$ar1 = array('lemons', 'oranges', 'grapes', 'pineapples');
$ar2 = array('carrots', 'onions', 'cabbage');
function mergeCustom($ar1, $ar2) {
    $newAr = array();
    foreach ($ar1 as $key => $item) {
        array_push($newAr, $item);
        if (!empty($ar2[$key])) {
            array_push($newAr, $ar2[$key]);
        }
    }
    // if length of second array is greater then first one
    while(!empty($ar2[$key])) {
        array_push($newAr, $ar2[$key]);
        $key++;
    }
    return $newAr;
}
var_dump(mergeCustom($ar1, $ar2), mergeCustom($ar2, $ar1));

输出为:

array(7) {
  [0]=>
  string(6) "lemons"
  [1]=>
  string(7) "carrots"
  [2]=>
  string(7) "oranges"
  [3]=>
  string(6) "onions"
  [4]=>
  string(6) "grapes"
  [5]=>
  string(7) "cabbage"
  [6]=>
  string(10) "pineapples"
}
array(8) {
  [0]=>
  string(7) "carrots"
  [1]=>
  string(6) "lemons"
  [2]=>
  string(6) "onions"
  [3]=>
  string(7) "oranges"
  [4]=>
  string(7) "cabbage"
  [5]=>
  string(6) "grapes"
  [6]=>
  string(6) "grapes"
  [7]=>
  string(10) "pineapples"
}