在PHP中将两个数组中的多个值转换为一个键
我想用ARRAY_COMBINE组合2个数组。我希望Array1的值是我的键,Array2的值是我的值。 这些值来自.yml文件,该文件以ComponentGroup为关键字,以ComponentName为值
$yamlKeys = array();
foreach ($yaml['components'] as $yamlComponent) {
array_push($yamlKeys, $yamlComponent['cachet']['componentgroup']);
}
$yamlValues = array();
foreach ($yaml['components'] as $yamlComponent) {
array_push($yamlValues, $yamlComponent['cachet']['componentname']);
}
$yamlMap = array();
$yamlMap = array_combine($yamlKeys, $yamlValues);
echo("===== YAML MAP STARTS =====");
var_dump($yamlMap);
echo("===== YAML MAP ENDS =====");
我的问题: 可以有同名的密钥。 在$yamlMap中,将只分配一个值(最后一个)。例如:
YAML文件如下所示:
FOO => BAR
Key1 => Value1
Key2 => Value2
FOO => BAZ
Key3 => Value3
我的代码:
FOO => BAZ
Key1 => Value1
Key2 => Value2
Key3 => Value3
但我希望是这样的:
FOO => BAR, BAZ
Key1 => Value1
Key2 => Value2
Key3 => Value3
更准确地说:如果有更多的"foo"键,我希望"foo"有更多的值(可能是值的数组)。
有什么想法吗?谢谢。
解决方案
$yamlMap = [];
foreach ($yaml['components'] as $yamlComponent) {
$key = $yamlComponent['cachet']['componentgroup'];
$value = $yamlComponent['cachet']['componentname'];
// Lets initialize the key to be an array so that we may collect multiple values
if(!array_key_exists($key, $yamlMap)) {
$yamlMap[$key] = [];
}
// lets add the value to the map under the key
$yamlMap[$key][] = $value;
}
https://3v4l.org/FtjQC
相关文章