如何在php中将两个数组与相应的递增键合并?

时间:2022-10-31 12:14:41

I have a two arrays in php

我在php中有两个数组

$arr1 = array(1=>332, 2=>333, 3=>74, 4=>78);
$arr2 = array(1=>'heading1', 3=>'heading2');

Note:Second array keys should not be changed.

注意:不应更改第二个数组键。

I need a output like below.

我需要一个像下面这样的输出。

array(
    1 => 'heading1',
    2 => 332,
    3 => 'heading2',
    4 => 333,
    5 => 74,
    6 => 78
)

Please help

2 个解决方案

#1


3  

This one gives the required output..

这个给出了所需的输出..

$arr1 = array(1=>332, 2=>333, 3=>74, 4=>78);
$arr2 = array(1=>'heading1', 3=>'heading2');
$arr3 = array();
$total = count($arr1) + count($arr2);
for($i=1; $i<= $total; $i++)
{
    if(isset($arr2[$i])) {
        $arr3[$i] = $arr2[$i];
        continue;
    }

    $arr3[$i] = array_shift($arr1);
}

print_r($arr3);

Codepad link

#2


1  

PHP Merge arrays

PHP合并数组

Have a look at that, see the examples on the page :)

看一下,看看页面上的例子:)

#1


3  

This one gives the required output..

这个给出了所需的输出..

$arr1 = array(1=>332, 2=>333, 3=>74, 4=>78);
$arr2 = array(1=>'heading1', 3=>'heading2');
$arr3 = array();
$total = count($arr1) + count($arr2);
for($i=1; $i<= $total; $i++)
{
    if(isset($arr2[$i])) {
        $arr3[$i] = $arr2[$i];
        continue;
    }

    $arr3[$i] = array_shift($arr1);
}

print_r($arr3);

Codepad link

#2


1  

PHP Merge arrays

PHP合并数组

Have a look at that, see the examples on the page :)

看一下,看看页面上的例子:)