2012-04-10 74 views
1

我有一個數組像這樣(抽象爲清楚起見):重複ASSOC數組值組合成一個附加的鍵

$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語句完成這個......是有更簡單的/更合適的方法?

回答

1

由於您對值進行「分組」,因此我構建了一個臨時數組$result,它將$foo中的值映射到$foo中的任何匹配鍵。這樣,通過它們的值識別重複項並連接它們的鍵是很簡單的。最後的array_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" 
} 
+0

所有這些解決方案都是比我在做什麼好,但關鍵是'array_flip' - 我錯過了這個功能,這實際上是我試圖完成的。感謝指針。 – k3davis 2012-04-13 18:09:28

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; 
} 

我的回答沒有太多優雅,但它會完成工作。

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