1, "begin" => "01/01"-6ren">
gpt4 book ai didi

php - 在 PHP 中按多维数组分组并用逗号连接结果(不创建不必要的逗号)

转载 作者:搜寻专家 更新时间:2023-10-31 21:49:22 26 4
gpt4 key购买 nike

我需要按两列对二维数组中的行进行分组,然后在每组中,我需要用逗号连接另一列的值。

请注意,在第三行中,诊断值为空。

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

)

关于php - 在 PHP 中按多维数组分组并用逗号连接结果(不创建不必要的逗号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46723327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com