2011-06-06 74 views
3

我有這個關聯數組,其中key2key5始終與key1具有相同的值。是否可以通過引用數組本身或任何其他建議來刪除值重複來設置它們的值?數組是否可以引用自己

$arr = array(
    'key1' => 'some value', 
    'key2' => 'some value', //same as key1 and will always stay as key1 
    'key3' => 'some other value', 
    'key4' => 'yet another', 
    'key5' => 'some value' //same as key1 and will always stay as key1 
); 
+4

如果他們永遠是一樣的,爲什麼你需要它在那裏的3倍? – barfoon 2011-06-06 03:00:59

+0

@barfoon,因爲我通過鍵檢查數組。即使內部我的腳本將其視爲'$ arr ['key1']',我仍需要'$ arr ['key3']'。 – switch 2011-06-06 03:21:14

回答

10

您可以在陣列已經被宣佈後應用& reference

$arr = array(...); 
$arr["key2"] = & $arr["key1"]; 
$arr["key5"] = & $arr["key1"]; 
+0

+1,謝謝你的提示,從來沒有意識到可以在數組中做到這一點。 – stefgosselin 2011-06-06 03:04:31

+1

嗯,雖然我仍在思考這種方法可能的實際應用,但我承認這對我來說是新事物。你走吧! ++ 1 – 2011-06-06 03:04:54

+3

注意,如果你'unset($ arr ['key1'])'然後'$ arr ['key1'] ='foo''其他兩個鍵不會被更新。 – Matthew 2011-06-06 03:10:20

相關問題