You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多个PHP数组合并为一个数组?

合并多个单元素数组为连续索引数组

问题背景

现有三个PHP单元素数组:

$arr1 = array(0 => 'test 1');
$arr2 = array(0 => 'test 2');
$arr3 = array(0 => 'test 3');

期望合并后得到:

array(
    0 => 'Test1',
    1 => 'Test2',
    2 => 'test3'
)

解决方案

方法1:利用array_merge()合并+自定义处理逻辑

array_merge()会自动重置合并后数组的索引,再结合array_map()处理每个值的格式:

// 定义原始数组
$arr1 = array(0 => 'test 1');
$arr2 = array(0 => 'test 2');
$arr3 = array(0 => 'test 3');

// 先合并数组
$temp = array_merge($arr1, $arr2, $arr3);

// 处理每个元素的格式
$result = array_map(function($item, $index) {
    $cleaned = str_replace(' ', '', $item);
    // 前两个元素首字母大写,第三个保留小写
    return $index < 2 ? ucwords($cleaned) : strtolower($cleaned);
}, $temp, array_keys($temp));

print_r($result);

执行后输出:

Array
(
    [0] => Test1
    [1] => Test2
    [2] => test3
)

方法2:手动遍历合并(适合数组数量动态变化的场景)

如果需要合并的数组数量不固定,可以把所有数组放进一个容器,遍历处理:

// 把所有要合并的数组放进一个大数组
$allArrays = [
    array(0 => 'test 1'),
    array(0 => 'test 2'),
    array(0 => 'test 3')
];

$result = [];
foreach ($allArrays as $idx => $singleArr) {
    $value = $singleArr[0];
    $processed = str_replace(' ', '', $value);
    // 根据索引调整格式
    $result[] = $idx < 2 ? ucwords($processed) : strtolower($processed);
}

print_r($result);

内容的提问来源于stack exchange,提问作者xoyiyep13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 03:10:48