转换 PHP 多维数组,使值成为键,其他值成为每个键的数组

Convert PHP multidimensional array so that the values become keys, and and other values become arrays for each key

我有:

    ['countryCode' => 11, 'postalCode' => 12345],
    ['countryCode' => 11, 'postalCode' => 12346],
    ['countryCode' => 11, 'postalCode' => 12347],
    ['countryCode' => 11, 'postalCode' => 12348],
    ['countryCode' => 11, 'postalCode' => 12349],
    ['countryCode' => 12, 'postalCode' => 12345],
    ['countryCode' => 12, 'postalCode' => 12346],
    ['countryCode' => 12, 'postalCode' => 12347],
    ['countryCode' => 12, 'postalCode' => 12348],
    ['countryCode' => 12, 'postalCode' => 12349],
];

但我想要:

    '11' => ['12345, 12346, 12347, 12348, 12349'], '12' => ['12345, 12346, 12347, 12348, 12349']
];

我试过:

$countries = array_column($data, 'countryCode');
$countries = array_unique($countries);
$countries = array_fill_keys($countries, []);

function makeArrays(&$countries, $data){
    foreach ($countries as $countryId => $postalCodes){
        foreach ($data as $item) {
            if ($item['countryCode'] == $countryId) {
                array_push($postalCodes, $item['postalCode']);
            }
        }
    }
    return $countries;
}

makeArrays($countries, $data);

当我 var_dump makeArrays 函数时,国家 ID 键没有像我期望的那样填充邮政编码数组:

array(2) {
  [11]=>
  array(0) {
  }
  [12]=>
  array(0) {
  }
}

如何让每个键的数组填充预期值?

您可以遍历数组并将值设置为键。

    $arr = [
    ['countryCode' => 11, 'postalCode' => 12345],
    ['countryCode' => 11, 'postalCode' => 12346],
    ['countryCode' => 11, 'postalCode' => 12347],
    ['countryCode' => 11, 'postalCode' => 12348],
    ['countryCode' => 11, 'postalCode' => 12349],
    ['countryCode' => 12, 'postalCode' => 12345],
    ['countryCode' => 12, 'postalCode' => 12346],
    ['countryCode' => 12, 'postalCode' => 12347],
    ['countryCode' => 12, 'postalCode' => 12348],
    ['countryCode' => 12, 'postalCode' => 12349],
]; 

//
$newArr = [];
foreach ($arr as $key => $val) {
    $newArr[$val['countryCode']][] = $val['postalCode'];
}
print_r($newArr);