我有以下数组:
$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 填充了 $output1 和 $output2 值,这样
$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 数组中选择一个随机变量,而不是按顺序遍历它。
您可以使用下标 (
[]
) 运算符引用数组的元素:
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;
}
}
试试这个。
$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 <= 6, $i++) {
$newarray .= $moods[$i % (count($moods) - 1)] == 'neutral' ? '1' : '0';
}