2014-05-20 62 views
0

我有一個數組,看起來像這樣:結合數組中的元素,由於相似的價值觀

array(
0 => headerOne:3 
1 => headerTwo:5 
2 => headerThree:6 
3 => headerFour:3 
4 => headerTwo:10 
) 

我有一個包含以「headerTwo」 我想要做的就是開頭的字符串兩個元素合併開頭的元素和相同的頭,然後在合併時從字符串中添加整數。所以,最終的結果會是這樣:

array(
0 => headerOne:3 
1 => headerTwo:15 
2 => headerThree:6 
3 => headerFour:3 
) 

我嘗試了許多方法,其中沒有一個似乎已經奏效......我有一種感覺,我一直在這樣做了錯誤的方式。有任何想法嗎?

+0

歡迎的StackOverflow!問題應該獨立存在,你的介紹並沒有增加任何內容(並且在人們尋找有關你的問題的快速信息的問題頁面上浪費了寶貴的屏幕空間!)。今後請不要使用這樣的介紹,我已經編輯了這個。 – BradleyDotNET

回答

1

與剛剛嘗試:

$input = array(
    'headerOne:3', 
    'headerTwo:5', 
    'headerThree:6', 
    'headerFour:3', 
    'headerTwo:10' 
); 
$temp = array(); 
$output = array(); 

foreach ($input as $data) { 
    list($key, $value) = explode(':', $data); 
    if (!isset($temp[$key])) { 
     $temp[$key] = 0; 
    } 
    $temp[$key] += (int) $value; 
} 

foreach ($temp as $key => $value) { 
    $output[] = $key . ':' . $value; 
} 


var_dump($output); 

輸出:

array (size=4) 
    0 => string 'headerOne:3' (length=11) 
    1 => string 'headerTwo:15' (length=12) 
    2 => string 'headerThree:6' (length=13) 
    3 => string 'headerFour:3' (length=12) 
+0

@Miss_New_Developer我更新了我的答案 - 請再次檢查。 – hsz

+0

感謝您的回答! :D sooo多!給予好評! –

+0

好酷,我不能upvote,因爲即時新哈哈,但這就是答案;) –