我是PHP的新手,我很难按数组进行分组。 事实上,我有一个多维度的患者阵列(“id”)住院(“开始”是住院日期),他们在那里有每个不同住院的诊断。
$data = array (
0 =>array("id"=>1, "begin"=>"01/01","diagnostic"=>"a"),
1 =>array("id"=>1, "begin"=>"01/01","diagnostic"=>"b"),
2 =>array("id"=>1, "begin"=>"01/01","diagnostic"=>""),
3 =>array("id"=>1, "begin"=>"02/02","diagnostic"=>"a"),
);
从列“id”和“begin”的那一刻起,我想用“逗号”连接“诊断”的值。 我想有这样的事情:
$output = array (
0 =>array("id"=>1, "begin"=>"01/01","diagnostic"=>"a, b"),
1 =>array("id"=>1, "begin"=>"02/02","diagnostic"=>"a"),
);
是的,请问有人帮帮我吗?
谢谢
答案 0 :(得分:0)
公平地说,你要求一个完整的解决方案。
所以,我快速了解如何完成它:
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
)
)