我想在特定模式后插入一个项目。在我的情况下,我想在数组中每隔一秒x
后插入a
。在第六次a
之后,我的代码无法正常运行:
$array = array("a","a","a","a","a","a","b","a","a");
$out = array();
foreach ($array as $key=>$value){
$out[] = $value; // add current letter to new array
if($value=='a' && $array[$key-1]=='a' && $out[$key] !='x'){ // check if current and last letter are a
$out[] = 'x'; // if so add an x to the array
}
}
print_r($out);
答案 0 :(得分:1)
最后纠正答案
你在寻找什么?
<?php
$array = array("a","a","a","a","a","a","b","a","a");
foreach ($array as $key => $value){
if ($key == 0 || $key == 1) {
$array[$key] = $value;
} elseif($array[$key-1] == 'a' && $array[$key-2] == 'a' && $array[$key] == 'a') {
$array[$key] = 'x';
} else {
$array[$key] = $value;
}
}
$count = count($array);
if ($array[$count-1] == 'a' && $array[$count-2] == 'a') {
$array[] = 'x';
}
print_r($array);
?>
如果我理解正确,请在2 a
之后将x
放入新数组中。
<强>更新强>
请立即查看。如果最后两个元素在数组中x
,则会添加一个新元素a
。
有例外,但仍然有效:
<?php
$array = array("a","a","a","a","a","a","b","a","a");
foreach ($array as $key => $value){
if($array[$key-1] == 'a' && $array[$key-2] == 'a' && $array[$key] == 'a') {
$array[$key] = 'x';
}
}
$count = count($array);
if ($array[$count-1] == 'a' && $array[$count-2] == 'a') {
$array[] = 'x';
}
print_r($array);
?>
更新 - 更正代码
我认为以下代码可以满足您的所有需求:
<?php
$arr = array("a","w","a","d","a","a","b","a","a", "w");
$arr_count = count($arr);
for ($i = 0; $i < $arr_count; $i++){
if (!empty($arr[$i+1]) && $arr[$i] == $arr[$i+1]) {
$first_half = array_slice($arr, 0, $i+2);
$second_half = array_slice($arr, $i+2, $arr_count);
if (count($second_half) > 0) {
$arr = array_merge($first_half, ["x"], $second_half);
}
}
}
$count = count($arr);
if ($arr[$count-1] == 'a' && $arr[$count-2] == 'a') {
$arr[] = 'x';
}
print_r($arr);
?>
答案 1 :(得分:0)