dongtuoao7987 2015-06-23 01:40
浏览 34
已采纳

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

I want the array to merge into a key value pair. look at the example below

Here is my code and array $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)

Here is my code:

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

the output is :

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

I want it to look like this:

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

I think I'm almost there but I guess I need some help.

  • 写回答

2条回答 默认 最新

  • douyun3887 2015-06-23 02:48
    关注

    This line does nothing because it is superseded just a bit later as the same variable is being set:

    $aExtraFilter2[$extrafilterkey] = [];
    

    This line appends to the array regardless of what you have as $value['key'], which is why you get all keys lumped together in the output:

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

    This will produce a desired output:

    // 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条)

报告相同问题?