2010-08-17 31 views
0

我希望在第一個具有值的第一個鍵之前將以下示例中具有o的值添加到鍵中o在數組中。就像這樣:如何在數組中添加一行值並移至上一個鍵PHP

$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

注意拼寫... array()不是aray .. – Manie 2010-08-17 07:37:54

+1

如果第一個值有一個o,它會怎樣? – Gumbo 2010-08-17 07:46:19

+0

爲什麼在第二個例子中'巧克力'被連接在一起? – NullUserException 2010-08-17 07:47:41

回答

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" 
} 

順便說一句r:擺脫通知(未定義偏移)所需的代碼留作練習。

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」

相關問題