在PHP中将两个数组中的多个值转换为一个键 [英] Multiple values to one key from 2 arrays in PHP

查看:0
本文介绍了在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

这篇关于在PHP中将两个数组中的多个值转换为一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆