To be fair, you are asking for a complete solution.
So here's my quick take on how to get it done:
http://sandbox.onlinephpfunctions.com/code/eb4fef6146b77fb7ff157790046c79750ef90cdb
<?php
$data = [
0 =>array("id"=>1, "begin"=>"01/01","diagnostic"=>"a", "procedure" => "x"),
1 =>array("id"=>1, "begin"=>"01/01","diagnostic"=>"b", "procedure" => ""),
2 =>array("id"=>1, "begin"=>"01/01","diagnostic"=>"a", "procedure" => "y"),
3 =>array("id"=>1, "begin"=>"02/02","diagnostic"=>"a", "procedure" => "z"),
];
// create an empty array to hold results
$result = [];
// iterate through each entry of the original $data
foreach($data as $entry){
// create a temporary array index, that will be unique across the entries conditions (begin, id)
$tempId = $entry['id'] . '-' . $entry['begin'];
// create and append entries to diagnostic and procedure
$result[$tempId]['diagnostic'][] = $entry['diagnostic'];
$result[$tempId]['procedure'][] = $entry['procedure'];
// copy data that is identical
$result[$tempId]['begin'] = $entry['begin'];
$result[$tempId]['id'] = $entry['id'];
}
// iterate through entries and implode unique, not empty elements of diagnostic and procedure array with a comma
foreach($result as &$entry){
$entry['diagnostic'] = implode(',', array_unique(array_filter($entry['diagnostic'])));
$entry['procedure'] = implode(',', array_unique(array_filter($entry['procedure'])));
}
print_r($result);
The above will produce:
Array
(
[1-01/01] => Array
(
[diagnostic] => a,b
[procedure] => x,y
[begin] => 01/01
[id] => 1
)
[1-02/02] => Array
(
[diagnostic] => a
[procedure] => z
[begin] => 02/02
[id] => 1
)
)