Muhammad Sanaullah Muhammad Sanaullah - 3 months ago 17
PHP Question

Find, Combine and sum the array value

I have a array its change value every time when new data come (its not from database). I want to calculate key 1 and key 2 value if the key 1 and key 3 matched even there is 5 array its return value in one, but i am confused how to do that, here is the array i have!

Array
(
[0] => Array
(
[0] => root
[1] => 0.0
[2] => 4428
[3] => sshd
)

[1] => Array
(
[0] => root
[1] => 12.5
[2] => 1192
[3] => sshd
)

[2] => Array
(
[0] => root
[1] => 0.0
[2] => 908
[3] => udevd
)

[3] => Array
(
[0] => root
[1] => 7
[2] => 776
[3] => udevd
)

[4] => Array
(
[0] => root
[1] => 0.0
[2] => 592
[3] => mingetty
)

[5] => Array
(
[0] => root
[1] => 2
[2] => 592
[3] => mingetty
)

[6] => Array
(
[0] => root
[1] => 0.0
[2] => 588
[3] => mingetty
)
[7] => Array
(
[0] => root
[1] => 0.0
[2] => 0
[3] => migration/0
)

[8] => Array
(
[0] => ntd
[1] => 0.0
[2] => 0
[3] => ksoftirqd/0
)

[9] => Array
(
[0] => root
[1] => 0.0
[2] => 0
[3] => ksoftirqd/0
)

}


I need an output like this:

Array
(
[0] => Array
(
[0] => root
[1] => 12.5
[2] => 5620
[3] => sshd
)


[1] => Array
(
[0] => root
[1] => 7
[2] => 1684
[3] => udevd
)

[2] => Array
(
[0] => root
[1] => 2
[2] => 1772
[3] => mingetty
)


[3] => Array
(
[0] => root
[1] => 0.0
[2] => 0
[3] => migration/0
)


[4] => Array
(
[0] => ntd
[1] => 0.0
[2] => 0
[3] => ksoftirqd/0
)

[5] => Array
(
[0] => root
[1] => 0.0
[2] => 0
[3] => ksoftirqd/0
)

}


IN detail:

I need to make a script/code to match all the array using key 0 and key 3 and both must be matched inside array.

Then we have to sum up key 1 value whit all the others found array key 1 and key 2 value with all the others found key 2.

I hope i explain it clearly, i need a solution if possible don't post code just give me a guide how its done.

I try different thing which i think should work but i terribly fail.

Answer

Start with this simple foreach:

$result_array = array();
foreach ($start_array as $item) {
    // create a unique pair
    $key = $item[0] . ':' . $item[3];

    if (!isset($result_array[$key])) {
        // if we met this key first - add `$item` as initial value
        $result_array[$key] = $item;
    } else {
        // else just add needed data:
        $result_array[$key][1] += $item[1];
        $result_array[$key][2] += $item[2];
    }
}
print_r($result_array);
// if you need numeric keys again - use `array_values()`.
print_r(array_values($result_array));
Comments