2017-04-13 9 views
0

str_replace、str_replace、または他のオプションを使用するのに最適なものは何ですか?str_replace、str_replace、または他のオプションを使用するのに最適なものは何ですか?

たとえば、私は空ではなく、XMLファイルに基づいてPHPによって生成された配列を持っています。変更が必要な変数があります。値が配列内にあり、変数に標準値がある場合、値は他の値(翻訳、他の単語など)に変更する必要があります。

<?php 
$ethnic_later = 'niet opgegeven'; 
$ethnic_array = array( 'Blank', 
         'getint', 
         'Aziatisch', 
         'Zuid-Amerikaans' 
        ); 
if (in_array('Blank', $ethnic_array) && $ethnic == 'Blank'){ 
    $ethnic = str_replace($ethnic, 'blanke', $ethnic); 
}elseif (in_array('getint', $ethnic_array) && $ethnic == 'getint'){ 
    $ethnic = str_replace($ethnic, 'getinte', $ethnic); 
}elseif (in_array('Aziatisch', $ethnic_array) && $ethnic == 'Aziatisch'){ 
    $ethnic = str_replace($ethnic, 'Aziatische', $ethnic); 
}elseif(in_array($ethnic, $ethnic_array) && $ethnic == 'Zuid-Amerikaans'){ 
    $ethnic = str_replace($ethnic, 'Zuid Amerikaanse', $ethnic); 
}else{ 
    $ethnic = str_replace($ethnic, $ethnic_later, $ethnic); 
} 

echo 'een mooie ' . $ethnic . ' kleur'; 
?> 

または私はちょうど下記のようなPHP関数str_replace()を使用せずに$ethnicの値を上書きすることができます:私は以下のコードでこれを行うことができ

<?php 
$ethnic_later = 'niet opgegeven'; 
$ethnic_array = array( 'Blank', 
         'getint', 
         'Aziatisch', 
         'Zuid-Amerikaans' 
        ); 
if (in_array('Blank', $ethnic_array) && $ethnic == 'Blank'){ 
    $ethnic = 'blanke'; 
}elseif (in_array('getint', $ethnic_array) && $ethnic == 'getint'){ 
    $ethnic = 'getinte'; 
}elseif (in_array('Aziatisch', $ethnic_array) && $ethnic == 'Aziatisch'){ 
    $ethnic = 'Aziatische'; 
}elseif(in_array($ethnic, $ethnic_array) && $ethnic == 'Zuid-Amerikaans'){ 
    $ethnic = 'Zuid Amerikaanse'; 
}else{ 
    $ethnic = $ethnic_later; 
} 

echo 'een mooie ' . $ethnic . ' kleur'; 
?> 

へのより多くの可能性があります。私は上記の2つを投稿しました... str_replace()を使用しない最後のオプションは、str_replace()より速いと信じています...

私の質問:PHPを使って欲しいことをやり遂げる最良の方法は何ですか?このような種類の仕事はどうしますか?

+0

「ホワイト」「ブラック」「イエロー」ftfy – user2176127

+0

@ user2176127はい、これは配列を作成するもう1つの方法ですが、読みやすくはありませんが、 'array( 'White'、 'Black'、 'Yellow '); '速い? – jagb

答えて

0

あなたは民族$をにおける期待値によってインデックス付けされた配列を作成し、文字列が含まれていますので、同じようにマップするために$民族の変数を希望:

<?php 
$ethnic_later = 'niet opgegeven'; 
$ethnic_array = array( 'Blank' => 'blanke', 
       'getint' => 'getinte', 
       'Aziatisch' => 'Aziatische', 
       'Zuid-Amerikaans' => 'Zuid Amerikaanse' 
       ); 
if (isset($ethnic_array[$ethnic])) { 
     $ethnic = $ethnic_array[$ethnic]; 
}else{ 
     $ethnic = $ethnic_later; 
} 

echo 'een mooie ' . $ethnic . ' kleur'; 

をあなたがしたいとき$ ethnicsをさらに追加し、配列に要素を追加します。

+0

入力いただきありがとうございます。コードは短く、速度も速いかもしれませんが、速度、 – jagb

関連する問題