2016-05-08 12 views
1

PHPで配列のキーの値を置き換えるソートルーチンを、別の配列のキー値と置き換える方法は、前の配列のキー値の順序が間違っている。私は$array2でcorrospondingコンテンツを$array1の値を置き換えることができますどのようにPHP配列の値を別の配列の値で置き換えます

$array1 = ['section2', 'section3', 'section1']; 
$array2 = ['content for section1', 'content for section2', 'content section3']; 

は、だから私は....私が求めていることは、私は....以下の順で

content for section2 
content for section3 
content for section1 

$array1ディスプレイを作ることができる方法です

+1

チェックこのマニュアルhttp://www.w3schools.com/php/func_string_str_replace.asp http://php.net /manual/en/function.str-replace.php –

+0

2つの配列の間にはどんな関係がありますか? section2の内容はサンプル値であるか、常に単語 'section2'で終わりますか? –

+0

2つの配列順序の間に関係がない場合、問題は解決されません。 –

答えて

1

ループ両方の配列を推測しているかどうかをチェック、keyに基づいて$array2値に$array1の値を変更するそうだとすれば、$array2をループしながら、$array1の値が存在するので、あなたは秩序を保つことができる、すなわち:

$array1 = ['section2', 'section3', 'section1']; 
$array2 = ['content for section1', 'content for section2', 'content for section3']; 

foreach($array1 as $key => $value){ 
    foreach($array2 as $key2 => $value2){ 
     if(preg_match("/$value/", $value2)){ 
      $array1[$key] = $value2; 
     } 
    } 
} 

print_r($array1); 

出力:

Array 
(
    [0] => content for section2 
    [1] => content for section3 
    [2] => content for section1 
) 

Ideone Demo

関連する問題