提问人:Icewaffle 提问时间:4/1/2023 最后编辑:Andy PrestonIcewaffle 更新时间:4/2/2023 访问量:54
PHP 顺序通过数组和 IF-Loop
php sequency through array with if-loop
问:
我有以下数组:
$moods = array("neutral", "happy", "sad");
$newarray= "";
我想使用一个 if 循环,它按顺序遍历数组$mood,并根据所选$moods值给出不同的输出
for ($x = 1; $x <= 7; $x++) {
[insert code for sequencing through $moods here]
if ($moods == "neutral") {
$output1 = "1";
$newarray.= $output1
}
else {
$output2 = "0";
$newarray.= $output2
}
所需的输出是$newarray填充了 $output 1 和 $output 2 值,使得
$newarray= "1001001";
我试过使用array_rand:
for ($x = 1; $x <= 7; $x++) {
$mood= array_rand($moods,1);
if ($mood == "neutral") {
$output1 = "1";
$newarray .= $output1
}
else {
$output2 = "0";
$newarray.= $output2
}
但这样做的问题在于,它从$moods数组中选择一个随机变量,而不是按顺序遍历它。
答:
1赞
Bulent
4/1/2023
#1
试试这个。
$moods = ['neutral', 'happy', 'sad'];
$newarray= '';
foreach($moods as $mood) {
$newarray .= $mood == 'neutral' ? '1' : '0';
}
根据更新的问题进行更新
$moods = ['neutral', 'happy', 'sad'];
$newarray= '';
// initail index should be 0 to access correct value in $moods
for($i = 0; $i <= 5; $i++) {
$newarray .= $moods[$i % (count($moods))] == 'neutral' ? '1' : '0';
}
评论
0赞
Icewaffle
4/1/2023
您将如何修改超过 3 次迭代?
0赞
Icewaffle
4/1/2023
使用更新的答案,我似乎得到了一个我无法识别的语法错误:语法错误,意外的标记“)”,期望“;”
1赞
Bulent
4/1/2023
这是一个错别字,已经修复了。
0赞
Icewaffle
4/1/2023
谢谢,但这给出了“1010101”的意外输出,而不是所需的1001001 - 另外,您能否解释一下在此过程中发生了什么 $moods[$i % (count($moods) - 1)] ?我真的不明白这串代码在做什么——尤其是代码的“$i%(计数)”部分。
1赞
Bulent
4/1/2023
我修复了代码。 计算模以获得索引。当 $i 为 1 且 count 为 3 时,它返回 1。当 $i 为 5 且计数为 3 时,它返回 2。php.net/manual/en/language.operators.arithmetic.php$i % (count($moods)
0赞
Mureinik
4/1/2023
#2
您可以使用下标 () 运算符引用数组的元素:[]
for ($x = 1; $x <= 3; $x++) {
$mood = $moods[i];
if ($mood == "neutral") { # Note that this should relate to $mood, not $moods
$output1 = "1";
$newarray.= $output1;
} else {
$output2 = "0";
$newarray.= $output2;
}
}
评论
"100"
"010"
neutral