首页 > 解决方案 > 将公共键的数据合并到同一个数组中

问题描述

所以我有一个这样的数组:-

$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;
}

任何帮助,将不胜感激。

标签: phparrays

解决方案


使用国家/地区值作为临时关联键来确定是否需要连接。

代码:(演示

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

推荐阅读