我需要将二维数组中的行按两列分组,然后在每组中,我需要用逗号连接另一列的值。
请注意,在第三行中,诊断值为空。
$data = [
["id" => 1, "begin" => "01/01", "diagnostic" => "a"],
["id" => 1, "begin" => "01/01", "diagnostic" => "b"],
["id" => 1, "begin" => "01/01", "diagnostic" => ""],
["id" => 1, "begin" => "02/02", "diagnostic" => "a"],
];
预期成果:
[
["id" => 1, "begin" => "01/01", "diagnostic" => "a, b"],
["id" => 1, "begin" => "02/02", "diagnostic" => "a"],
]
公平地说,您要求一个完整的解决方案。
因此,以下是我对如何完成它的快速看法:
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);
以上将产生:
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
)
)
与通常的"分组和追加/连接"问题相比,此任务略有不同,因为您希望避免在组中存在空诊断值时编写不必要的逗号。 经典(最佳)方法是使用两个标识行值形成唯一字符串,并将该字符串作为结果数组中的第一级"分组键"应用。
每次遇到id
值和begin
值的组合时,都需要将行数据推送到组中并正确设置格式。
这里的额外步骤是,您必须检查当前diagnostic
值的长度,并检查组diagnostic
值的长度,以确定是否需要在新值之前附加逗号。
不需要太多的想象力就可以理解使用单个循环将优于使用多个循环和array_column()
调用。
代码:(演示)
$result = [];
foreach ($data as $row) {
$compositeKey = $row['id'] . '-' . $row['begin'];
if (!isset($result[$compositeKey])) {
$result[$compositeKey] = $row;
} elseif (strlen($row['diagnostic'])) {
$result[$compositeKey]['diagnostic'] .= (strlen($result[$compositeKey]['diagnostic']) ? ', ' : '') . $row['diagnostic'];
}
}
var_export(array_values($result));
输出:
array (
0 =>
array (
'id' => 1,
'begin' => '01/01',
'diagnostic' => 'a, b',
),
1 =>
array (
'id' => 1,
'begin' => '02/02',
'diagnostic' => 'a',
),
)