PHP 顺序通过数组和 IF-Loop

php sequency through array with if-loop

提问人:Icewaffle 提问时间:4/1/2023 最后编辑:Andy PrestonIcewaffle 更新时间:4/2/2023 访问量:54

问:

我有以下数组:

$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数组中选择一个随机变量,而不是按顺序遍历它。

PHP 序列

评论

1赞 Kaddath 4/1/2023
所以,为了清楚起见,你希望你的输出是一个二进制字符串(如果中立,如果快乐')?但是你的代码中似乎没有可以比较的值。似乎也不清楚为什么需要这个输出"100""010"
0赞 Icewaffle 4/1/2023
不完全是,如果输出是“中性”[1]、“快乐”[0]、“悲伤”[0],$moods我希望输出是“100”的字符串。如果$moods是(“中性”、“中性”、“快乐”),我会想要和输出“110”。为了清楚起见,我已经编辑了原始帖子(超过 3 次迭代)
0赞 nice_dev 4/1/2023
因此,您希望将每个第 3 个值选为 ?neutral
0赞 nice_dev 4/1/2023
如果您只想要一个二进制字符串,那么只需创建一个。$moods等有什么意义?
0赞 Icewaffle 4/1/2023
是的,我希望每个 3 个值被选为中性值,以及每个 3 个值(从第 2 次迭代开始)被选为快乐值,每 3 个值被选为悲伤值。

答:

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;
    }
}