如何用值数组替换数组中的值

时间:2019-09-19 21:04:00

标签: php arrays

例如,我有一个值数组

$fred = Array('one','two','@group','three','four');

和第二个数组

$group = Array('alpha','beta','gamma');

哪个是用$ group数组中的值替换值'@group'的最有效方法?也就是说,获得

$expanded_fred = Array('one','two','alpha','beta','gamma','three','four');

PS分组方法只有一个级别。没有嵌套的组。

2 个答案:

答案 0 :(得分:1)

首先让我们使用array_search查找@group元素的键:

$replaceKey = array_search('@group', $fred);

接下来,我们将使用array_splice@group数组替换$group元素:

array_splice($fred, $replaceKey, 1, $group);

$fred现在是您的扩展数组。

此处演示:https://3v4l.org/qf4ts

答案 1 :(得分:1)

您可以迭代$fred来查找所有@group并将其替换为$groupDemo

$result = [];
$fred = Array('one','two','@group','three','four');
$group = Array('alpha','beta','gamma');
foreach($fred as $value){
    if($value == '@group'){
        $result = array_merge($result,$group);
    }else{
        $result[] = $value;
    }
}
print_r($result);
相关问题