在php中将数组值合并为单个键和多个值

时间:2015-06-23 01:40:09

标签: php arrays

我希望数组合并为键值对。看下面的例子

这是我的代码和数组$ aExtraFilter

array (size=4)
  0 => 
    array (size=2)
      'key' => string 'CookTech' (length=8)
      'value' => string 'Broil' (length=5)
  1 => 
    array (size=2)
      'key' => string 'CookTech' (length=8)
      'value' => string 'Pan Fry' (length=7)
  2 => 
    array (size=2)
      'key' => string 'CookSkills' (length=10)
      'value' => string 'Intro' (length=5)
  3 => 
    array (size=2)
      'key' => string 'CookSkills' (length=10)
      'value' => string 'Knife Skills' (length=12)

这是我的代码:

    $aExtraFilter2 = [];
    $extrafilterkey = '';
    $extrafiltervalue = [];
    foreach ($aExtraFilter as $key => $value) {
        $extrafilterkey = $value['key'];
        $aExtraFilter2[$extrafilterkey] = [];
        array_push($extrafiltervalue, $value['value']);
        $aExtraFilter2[$extrafilterkey] = implode(',', $extrafiltervalue);
    }
    var_dump($aExtraFilter2);

输出是:

array (size=2)
  'CookTech' => string 'Broil,Pan Fry' (length=13)
  'CookSkills' => string 'Broil,Pan Fry,Intro,Knife Skills' (length=32)

我希望它看起来像这样:

array (size=2)
  'CookTech' => string 'Broil,Pan Fry' (length=13)
  'CookSkills' => string 'Intro,Knife Skills' (length=32)

我想我差不多了,但我想我需要一些帮助。

2 个答案:

答案 0 :(得分:1)

这一行什么都不做,因为稍后因为设置相同的变量而被取代:

$aExtraFilter2[$extrafilterkey] = [];

此行附加到数组,无论您拥有$value['key']的内容,这就是为什么您将所有键集中在输出中的原因:

array_push($extrafiltervalue, $value['value']);

这将产生所需的输出:

// fill array of arrays
$aExtraFilter2 = [];
foreach ($aExtraFilter as $key => $value) {
    if (!array_key_exists($value['key'], $aExtraFilter2)) $aExtraFilter2[$value['key']] = [];
    $aExtraFilter2[$value['key']][] = $value['value'];
}
// convert to string (if needed at all, depends on what you're doing later)
foreach ($aExtraFilter2 as $key => $set) {
    $aExtraFilter2[$key] = join(',', $set);
}

答案 1 :(得分:1)

对此进行编码的典型方法是创建一个基于密钥的临时结构,并包含一个包含值的数组:

$tmp = [];
foreach ($aExtraFilter as $pair) {
    $tmp[$pair['key']][] = $pair['value'];
}

之后结构如下:

[
    'CookTech' => ['Broil', 'Pan Fry'],
    'CookSkills' => ['Intro', 'Knife Skills'],
]

然后,将该数组映射到您想要的表示形式:

$aExtraFilter2 = array_map(function($values) {
    return join(',', $values);
}, $tmp);

另请参阅:array_map()