我希望将以下示例中带有o的值添加到第一个键之前的键中,该键在数组中具有值为o的值。像这样:
$arr = array(
0 => 'apple',
1 => 'pear',
2 => 'orange',
3 => 'octopus',
4 => 'pineapple'
)
$arr = array(
0 => 'apple',
1 => 'pearorangeoctopus',
2 => 'Pineapple'
)
但是具有o的行数可以是可变的,并且在那里可以多次。
$arr = array(
0 => 'apple',
1 => 'pear',
2 => 'orange',
3 => 'octopus',
4 => 'pineapple',
5 => 'blueberry',
6 => 'pumpkin',
7 => 'chocolate',
8 => 'icecream'
)
$arr = array(
0 => 'apple',
1 => 'pearorangeoctopus',
2 => 'pineapple',
3 => 'blueberry',
4 => 'pumpkinchocolate',
5 => 'icecream'
)
有人有个主意吗? :)
答案 0 :(得分:0)
尝试这样的事情:
$arr = array(...);
$new_arr = array();
$o_index = false;
foreach($arr as $key=>$item){
if($item[0]=='o'){
if(!$o_index)
$o_index = $key-1;
$new_arr[$o_index] .= $item
}else{
$new_arr[$key] = $item;
}
}
请注意,如果您的钥匙不是连续的号码,或者第一个钥匙以“o”开头,则会出现问题
答案 1 :(得分:0)
$result = array();
$currentIndex = 0;
$item = $arr[$currentIndex];
while ($currentIndex < count($arr)) {
$nextItem = $arr[$currentIndex+1];
if (strpos($nextItem, 'o') !== false) {
$item .= $nextItem;
}
else {
$result[] = $item;
$item = $arr[$currentIndex+1];
}
$currentIndex++;
}
如果您的第二种情况的解决方案是:
,这可能就是您正在寻找的array(6) {
[0]=> "apple"
[1]=> "pearorangeoctopus"
[2]=> "pineapple"
[3]=> "blueberry"
[4]=> "pumpkinchocolate"
[5]=> "icecream"
}
BTW为了清楚起见:删除通知(未定义的偏移量)所需的代码留作练习。