I have an array that looks like this:
array(
0 => headerOne:3
1 => headerTwo:5
2 => headerThree:6
3 => headerFour:3
4 => headerTwo:10
)
I have TWO elements that contain a string that starts with "headerTwo" What I'm trying to do is to merge the elements where it starts with the same header and then ADD the integers from the string when they merge. So the end result would be like this:
array(
0 => headerOne:3
1 => headerTwo:15
2 => headerThree:6
3 => headerFour:3
)
I tried a number of ways, none of them seemed to have worked... and I have a feeling, that I've been doing it the wrong ways. Any ideas?
Just try with:
$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);
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)