例如,我有一个值数组
$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分组方法只有一个级别。没有嵌套的组。
答案 0 :(得分:1)
首先让我们使用array_search
查找@group
元素的键:
$replaceKey = array_search('@group', $fred);
接下来,我们将使用array_splice
用@group
数组替换$group
元素:
array_splice($fred, $replaceKey, 1, $group);
$fred
现在是您的扩展数组。
答案 1 :(得分:1)
您可以迭代$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);