work
とを除くすべての配列値を 0 に置き換えたいhome
。
入力:
$array = ['work', 'homework', 'home', 'sky', 'door']
私のコーディングの試み:
$a = str_replace("work", "0", $array);
期待される出力:
['work', 0, 'home', 0, 0]
また、入力データはユーザーの送信からのものであり、配列要素の量が非常に多い場合があります。
もう少しエレガントで短いソリューション。
$aArray = array('work','home','sky','door');
foreach($aArray as &$sValue)
{
if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}
& 演算子は、配列内の特定の元の文字列へのポインターです。(その文字列のコピーの代わりに)配列内の文字列に新しい値を割り当てることができます。unset() やキー操作など、配列内の順序を乱す可能性のあるものだけを行ってはなりません。
上記の例の結果の配列は次のようになります。
$aArray = array('work','home', 0, 0)
ループは一連のアクションを何度も実行します。したがって、配列内の各要素について、変更したい要素と等しいかどうかを確認し、等しい場合は変更します。また、文字列を必ず引用符で囲んでください
//Setup the array of string
$asting = array('work','home','sky','door')
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work' || $asting[$i] == 'home')
$asting[$i] = 0;
}
推奨される読書は次のとおりです。
http://www.php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/language.control-structures.php
しかし、ループなどに苦労している場合は、プログラミングの入門資料を読みたいと思うかもしれません。これは、何が起こっているのかを本当に理解するのに役立ちます。
もう少し他のはるかに速い方法ですが、本当は、ループが必要です:
//Setup the array of string
$asting = array('bar', 'market', 'work', 'home', 'sky', 'door');
//Setup the array of replacings
$replace = array('home', 'work');
//Loop them through str_replace() replacing with 0 or any other value...
foreach ($replace as $val) $asting = str_replace($val, 0, $asting);
//See what results brings:
print_r ($asting);
出力します:
Array
(
[0] => bar
[1] => market
[2] => 0
[3] => 0
[4] => sky
[5] => door
)
array_map を使用した代替:
$original = array('work','home','sky','door');
$mapped = array_map(function($i){
$exclude = array('work','home');
return in_array($i, $exclude) ? 0 : $i;
}, $original);
for ループのちょっとしたポイントです。多くの人は、新しい反復ごとに 2 番目の比較タスクが行われることを認識していません。したがって、大きな配列または計算の場合は、次のようにしてループを少し最適化できます。
for ($i = 0, $c = count($asting); $i < $c; $i++) {...}
コードが本当に最終的なものでない限り、元の問題についてはhttp://php.net/manual/en/function.array-replace.phpも参照してください:)
str_replace のパラメーター 1 と 2 として配列を指定することもできます...
これが私の最終的なコードです
//Setup the array of string
$asting = array('work','home','sky','door','march');
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
$asting[$i] = 20;
} elseif($asting[$i] == 'home'){
$asting[$i] = 30;
}else{
$asting[$i] = 0;
}
echo $asting[$i]."<br><br>";
$total += $asting[$i];
}
echo $total;