php - 将公共键的数据合并到同一个数组中
问题描述
所以我有一个这样的数组:-
$headers = array();
$headers[] = array("country" => "Netherlands", "city" => "Amsterdam");
$headers[] = array("country" => "Netherlands", "city" => "Tillsburg");
$headers[] = array("country" => "Sweden", "city" => "Stockholm");
我需要它:-
array("country" => "Netherlands", "city" => "Amsterdam,Tillsburg");
array("country" => "Sweden", "city" => "Stockholm");
如何合并值?
这是我到目前为止所尝试的,但它似乎不起作用。
function merge($headers) {
$final = [];
foreach($headers as $current) {
if(!in_array($current['country'], $final)) {
$final[] = $current['country'];
}
}
foreach($headers as $current) {
$final[$current['country']]['city'] = $current['city'];
}
return $final;
}
任何帮助,将不胜感激。
解决方案
使用国家/地区值作为临时关联键来确定是否需要连接。
代码:(演示)
$headers[] = array("country" => "Netherlands", "city" => "Amsterdam");
$headers[] = array("country" => "Netherlands", "city" => "Tillsburg");
$headers[] = array("country" => "Sweden", "city" => "Stockholm");
foreach ($headers as $row) {
if (!isset($result[$row['country']])) {
$result[$row['country']] = $row; // store the whole row
} else {
$result[$row['country']]['city'] .= ",{$row['city']}"; // concatenate
}
}
var_export(array_values($result)); // reindex the output array
输出:
array (
0 =>
array (
'country' => 'Netherlands',
'city' => 'Amsterdam,Tillsburg',
),
1 =>
array (
'country' => 'Sweden',
'city' => 'Stockholm',
),
)
推荐阅读
- c# - DocuSign 推荐的 DateSigned 选项卡值解析
- html - flexbox列内的高度相等?
- php - 从 PHP 中的复选框中检查多个值
- python - 如何使用mechanicalsoup 拍照?
- python - 使用 Pandas GroupBy 和 value_counts 查找最常见的值
- javascript - 减少三元运算符的代码
- python - 如何使用 BeautifulSoup 写入文件非英语语言
- python - python如何从这个文件中形成dict
- windows - 在 @INC 中找不到 Class/CSV.pm
- ios - Swift 内容标签?