-2

i have array multi-dimensional like this and i want sum all column "quota" values have same id and same ip and same visited 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,
    )
);

and i want result like this

$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,
        ),
    );

i need your help

1 Answers1

1

Loop the array and build a compound of id and ip in an associative array.
After the loop reset keys with array_values.

Edit didn't see you wanted visited ip also. Added it to the compound associative array keys.

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);

Output:

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)
  }
}

https://3v4l.org/5PDXp

Andreas
  • 23,610
  • 6
  • 30
  • 62