2012-11-20 27 views
3

我想用字符串鍵重寫數組「foo」的數字鍵。關係被保存在另一個數組「bar」中。用另一個數組重寫數組的鍵

$foo = array(
1 => 'foo', 
2 => 'bar', 
... 
); 

$bar = array(
1 => 'abc', 
2 => 'xyz', 
... 
); 

$result = array(
'abc' => 'foo', 
'xyz' => 'bar', 
... 
); 

達到這個結果的最快方法是什麼?

回答

1

空指針的例子,如果在兩個數組($ foo和$ bar)的鍵/值會在不同的順序將失敗。試想一下:

$foo = array(
    1 => 'foo', 
    2 => 'bar', 
); 

$bar = array(
    2 => 'xyz', 
    1 => 'abc', 
); 

如果運行array_combine($foo, $bar)像以前一樣,輸出將是

array(2) { 
    ["foo"]=> 
    string(3) "xyz" 
    ["bar"]=> 
    string(3) "abc" 
} 

這種簡單的循環,但是,應該工作:

$output = array(); 
foreach ($bar as $from => $to) { 
    $output[$to] = $foo[$from]; 
} 
+0

爲什麼不'ksort'兩個數組? :P – cHao

+0

請注意,OP明確定義了數組索引('1 =>'),所以我想我們可以假設它已經被處理了,除此之外我們總是可以*重新索引這兩個數組(例如'array_values')。 'array_combine'似乎是簡短而簡單的解決方案,至少對我而言。 – Zbigniew

7

使用array_combine功能:

$combined = array_combine($bar, $foo); 

print_r($combined);

Array 
(
    [abc] => foo 
    [xyz] => bar 
) 
相關問題