[英]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.