# 关于我们

## 新闻公告

< 返回

### PHP实现合并数组的方法有哪些

#### 1.arrary_merge

```\$arr1 = array(1, 2, 3, 4, 5);
\$arr2 = array(1, 2, 6, 7, 8, 9, 10);
\$result1 = array_merge(\$arr1, \$arr2);

\$arr3 = array("name" => "itbsl", "age" => 13, "sex" => "Male");
\$arr4 = array("name" => "火龙果", "age" => 13, "sex" => "Male");
\$result2 = array_merge(\$arr3, \$arr4);

echo "<pre>";
var_dump(\$result1);
var_dump(\$result2);```

#### 2.通过`+`合并

```\$arr1 = array(1, 2, 3, 4, 5);
\$arr2 = array(1, 2, 6, 7, 8, 9, 10);
\$result1 = \$arr1 + \$arr2;

\$arr3 = array("name" => "itbsl", "age" => 13, "sex" => "Male");
\$arr4 = array("name" => "火龙果", "age" => 13, "sex" => "Male", "id" => "411521");
\$result2 = \$arr3 + \$arr4;

echo "<pre>";
var_dump(\$result1);
var_dump(\$result2);```

#### 3.连接两个数组

`array_combine()`函数会得到一个新数组，它由一组提交的键和对应的值组成。

```\$arr1 = array("A","B","C","D");
\$arr2 = array("paul","itbsl","Golang","PHP");
\$result = array_combine(\$arr1,\$arr2);
echo '<pre>';
var_dump(\$result);```

#### 4.递归追加数组

`array_merge_recursive()`函数与`array_merge()`相同，可以将两个或多个数组合并在一起，形成一个联合的数组．两者之间的区别在于，当某个输入数组中的某个键己经存在于结果数组中时该函数会采取不同的处理方式．`array_merge()`会覆盖前面存在的键/值对，替换为当前输入数组中的键/值对，而`array_merge_recursive()`将把两个值合并在一起，形成一个新的数组，并以原有的键作为数组名。

```\$arr3 = array("name" => "itbsl", "age" => 13, "sex" => "Male");
\$arr4 = array("name" => "火龙果", "age" => 13, "sex" => "Male");
\$result2 = array_merge_recursive(\$arr3, \$arr4);

echo "<pre>";
var_dump(\$result2);```

/template/Home/Dawn/PC/Static