我有一个数组,每当新数据到来时它就会改变数值(它不是来自数据库)。我想计算键1和键2值,如果键1和键3匹配,即使有5个数组,它返回一个值,但我很困惑如何做到这一点,这是我有的数组:
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
)
}
我需要这样的输出:
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
)
}
详细说明:
我需要创建一个脚本/代码来匹配使用键0和键3的所有数组,并且两者必须在数组内匹配。
然后我们必须总结key 1值,其他所有其他人找到数组键1和键2值,其他所有其他值找到键2。
我希望我能清楚地解释清楚,如果可能的话,我需要一个解决方案,不要发布代码,只是给我一个指导,告诉我们它是如何完成的。
我尝试了不同的东西,我认为应该有效,但我非常失败。
答案 0 :(得分:0)
从这个简单的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));