2017-09-22 197 views
-2

替換具有多個陣列陣列我有主陣列,我想替換PHP通過鍵

Array 
(
    [0] => {title-1} 
    [1] => zebra 
    [2] => {title-1} 
    [3] => fruit 
    [4] => {title-2} 
    [5] => cars 
    [6] => {title-3} 
    [7] => city 
    [8] => {title-3} 
    [9] => amazing 
    [10] => gold 
    [11] => {title-2} 
) 

,然後我有3個陣列那樣

Array 
    (
     [0] => Blue 
     [2] => Red 
    ) 
    Array 
    (
     [6] => lamborghini 
     [8] => bugati 

    ) 
    Array (

    [4] => Yellow 
    [11] => dodge 
) 

我要輸出像那

(
     [0] => blue 
     [1] => zebra 
     [2] => red 
     [3] => fruit 
     [4] => yellow 
     [5] => cars 
     [6] => lamborghini 
     [7] => city 
     [8] => bugati 
     [9] => amazing 
     [10] => gold 
     [11] => dodge 
    ) 

我嘗試使用array_replace_recursive()但只適用於一個數組 可以幫助我的任何人

回答

0

要使用array_replace_recursive這兩個數組鍵都應該是相同的。參考下面的代碼。

$base = array('0' => '{title-1}', '1' => 'zebra','2'=>'{title-1}','3'=> 'fruit','4' => '{title-2}',5 => 'cars',6 => '{title-3}',7 => 'city'); 
$tem=array (0 => 'Blue', 2 => 'Red') ; 

$tem1=array (4 => 'Yellow',6 => 'dodge'); 

$basket = array_replace_recursive($base, $tem); 
$basket1 = array_replace($basket, $tem1); 
print_r($basket1); 

輸出:

Array 
(
    [0] => Blue 
    [1] => zebra 
    [2] => Red 
    [3] => fruit 
    [4] => Yellow 
    [5] => cars 
    [6] => dodge 
    [7] => city 
) 
0

正如你說你有3個數組至極確實包含你的主數組值。沒有任何回憶要做。

您可以簡單地使用 「陣列替換」:

$arrayMain = array(0 => "{title-1}", 1 => "zebra", 2 => "{title-1}"); 
$arrayReplace = array(0 => "Blue", 2 => "Red"); 

$finishedArray = array_replace($arrayMain, $arrayReplace); 

這會給你:

array(
    0 => "Blue", 
    1 => "zebra", 
    2 => "Red", 
); 

實際上,你可以用它來從多個陣列像array_replace取代多個array_keys($ mainArray ,$ replaceArray1,$ replaceArray2);等等。

檢查PHP文檔: http://php.net/manual/en/function.array-replace.php