How to add up a row of values in an array and move to the previous key PHP
I would like the value that has an o in the following example to be added to the key before the first key that has a value with an o in the array. Like this:
$arr = array(
0 => 'apple',
1 => 'pear',
2 => 'orange',
3 => 'octopus',
4 => 'pine开发者_如何学编程apple'
)
$arr = array(
0 => 'apple',
1 => 'pearorangeoctopus',
2 => 'Pineapple'
)
But the amount of rows that has an o can be variable and multiple times in there..
$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'
)
anyone got an idea? :)
$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++;
}
This is probably what you're looking for, if the solution for your second case is :
array(6) {
[0]=> "apple"
[1]=> "pearorangeoctopus"
[2]=> "pineapple"
[3]=> "blueberry"
[4]=> "pumpkinchocolate"
[5]=> "icecream"
}
BTW Just to be clear : the code needed to get rid of the Notice (Undefined offset) is left as an exercise.
Try something like this:
$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;
}
}
Have in mind that this will make problems if your keys are not consecutive numbers or the first key starts with 'o'
精彩评论