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

在PHP中如何将数组内的指定值Other替换为另一数组的全部值

PHP数组替换实现方案

以下是可直接运行的实现代码:

<?php
// 定义原始数组
$originalArray = ['abc', 'xyz', 'Other', 'Other', 'pqr'];
// 定义用来替换Other的目标数组
$replaceContent = ['lmnsa', 'asda'];
// 初始化结果存储数组
$result = [];

foreach ($originalArray as $item) {
    if ($item === 'Other') {
        // 遇到值为Other的元素时,将整个替换数组的内容追加到结果中
        array_push($result, ...$replaceContent);
    } else {
        // 非Other元素直接存入结果数组
        $result[] = $item;
    }
}

// 打印结果验证效果
print_r($result);
?>

运行后输出结果如下:

Array
(
    [0] => abc
    [1] => xyz
    [2] => lmnsa
    [3] => asda
    [4] => lmnsa
    [5] => asda
    [6] => pqr
)

低版本PHP兼容写法

如果你的PHP版本低于7.4不支持展开运算符...,可以改用array_merge实现替换内容追加:

<?php
$originalArray = ['abc', 'xyz', 'Other', 'Other', 'pqr'];
$replaceContent = ['lmnsa', 'asda'];
$result = [];

foreach ($originalArray as $item) {
    if ($item === 'Other') {
        $result = array_merge($result, $replaceContent);
    } else {
        $result[] = $item;
    }
}

print_r($result);
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:06:07