我具有这样的多维数组,我想对所有“ quota”列的值求和,它们具有相同的id,相同的ip和相同的访问的ip
$array = array(
"0" => array(
"id" => 1,
"ip" => 10.40.47.5,
"visited_ip" => 10.40.40.10,
"quota" => 20,
),
"1" => array(
"id" => 2,
"ip" => 10.40.47.20,
"visited_ip" => 10.40.40.10,
"quota" => 10,
),
"2" => array(
"id" => 1,
"ip" => 10.40.47.5,
"visited_ip" => 10.40.40.10,
"quota" => 30,
)
);
我想要这样的结果
$array = array(
"0" => array(
"id" => 1,
"ip" => 10.40.47.5,
"visited_ip" => 10.40.40.10,
"quota" => 50,
),
"1" => array(
"id" => 2,
"ip" => 10.40.47.20,
"visited_ip" => 10.40.40.10,
"quota" => 10,
),
);
我需要您的帮助
答案 0 :(得分:1)
环绕数组,并在关联数组中构建id和ip的复合。
循环后,使用array_values重置键。
编辑没有看到您也想访问ip。将其添加到复合关联数组键中。
foreach($array as $item){
if(!isset($res[$item['id'] . ' ' . $item['ip']] . " " . "visited_ip")){
$res[$item['id'] . ' ' . $item['ip'] . " " . "visited_ip"] = $item;
}else{
$res[$item['id'] . ' ' . $item['ip'] . " " . "visited_ip"]['quota'] += $item['quota'];
}
}
$res = array_values($res);
var_dump($res);
输出:
array(2) {
[0]=>
array(4) {
["id"]=>
int(1)
["ip"]=>
string(10) "10.40.47.5"
["visited_ip"]=>
string(11) "10.40.40.10"
["quota"]=>
int(50)
}
[1]=>
array(4) {
["id"]=>
int(2)
["ip"]=>
string(11) "10.40.47.20"
["visited_ip"]=>
string(11) "10.40.40.10"
["quota"]=>
int(10)
}
}