简体   繁体   English

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

[英]How to substitute a value in an array with an array of values

I have an array of values, for example我有一个值数组,例如

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

and a second array和第二个数组

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

Which is the most efficient way to substitute the value '@group' with the values inside $group array?用 $group 数组中的值替换值“@group”的最有效方法是什么? That is, to obtain也就是说,要获得

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

PS The grouping method has only one level. PS 分组方式只有一层。 No nested groups.没有嵌套组。

First lets use array_search to find the key of the @group element:首先让我们使用array_search来查找@group元素的键:

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

Next we'll use array_splice to replace the @group element with the $group array:接下来我们将使用array_splice@group元素替换为$group数组:

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

$fred is now your expanded array. $fred现在是您的扩展数组。

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

You can iterate the $fred to find all @group to replace them with $group .您可以迭代$fred以查找所有@group以将它们替换为$group Demo 演示

$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM