1

我有一个这样的数组(为清楚起见进行了抽象):

$foo = array(
   'breakfast' => 'a daily meal',
   'lunch' => 'a daily meal',
   'dessert' => 'a special treat',
   'snack' => 'a special treat',
   'plates' => 'tableware'
);

为此,我想将所有重复值的键组合成一个“合并”键 -print_r($foo);就像这样:

Array
(
[breakfast|lunch] => 'a daily meal'
[dessert|snack] => 'a special treat'
[plates] => 'tableware'
)

目前我正在通过一长串嵌套的丑陋 foreach 语句来实现这一点……有没有更简单/更合适的方法?

4

3 回答 3

1

我认同。从您的 $foo 我们添加...

$collector = array();
$newFoo = array();
foreach ($foo as $key=>$value){
    if (isset($collector[$value])){
        $collector[$value] .= '|'.$key;
    } else {
        $collector[$value] = $key;
    }
}

foreach ($collector as $keyValue=>$itemIndex){
    $newFoo[$itemIndex] = $keyValue;
}

我的回答没有太多优雅,但它会完成工作。

于 2012-04-10T17:32:50.163 回答
1

由于您正在对值进行“分组”,因此我构建了一个临时数组$result,将值映射$foo$foo. 这样,通过它们的值识别重复项并连接它们的键就很简单了。最后的 anarray_flip将返回您正在寻找的内容。

function merge_values(array $arr) {
    $result = array();

    foreach ( $arr as $key => $val ) {
        if ( isset($result[$val]) )
            $result[$val] .= '|' . $key;
        else
            $result[$val] = $key;
    }

    return array_flip($result);
}

查看结果:http: //ideone.com/iTUFY

array(3) {
  ["breakfast|lunch"]=>
  string(12) "a daily meal"
  ["dessert|snack"]=>
  string(15) "a special treat"
  ["plates"]=>
  string(9) "tableware"
}
于 2012-04-10T17:32:53.090 回答
0

像这样,可能是:

$foo = array(
   'breakfast' => 'a daily meal',
   'lunch' => 'a daily meal',
   'dessert' => 'a special treat',
   'snack' => 'a special treat',
   'plates' => 'tableware'
);
$new = array();
foreach($foo as $key => $value){
    $keyNew = array_search($value,$new);
    if ($keyNew){
        unset($new[$keyNew]);
        $new[$keyNew . "|" . $key] = $value;
    }else
        $new[$key] = $value;
}
print_r($new);
于 2012-04-10T17:35:41.640 回答