使用x个索引循环遍历PHP数组,但总是返回3个结果


Looping through PHP array with x indexes, but always returning 3 results

我有一个随机单词数的数组。它至少可以包含一个单词,也可以包含10个以上的单词。示例:

$words = array (
 0 => 'This',
 1 => 'is',
 2 => 'my',
 3 => 'word'
)

现在,假设我想从这个数组中回声出6个单词,当我们到达数组的末尾时重新开始。我希望逻辑类似于

for ($i=0; $i < 6 ; $i++) { 
    //if $words[$i] exist, print it, else reset the array and start over until we reach all 6
}

我希望结果是:"这是我的话,这是">

我很难算出这方面的数学。任何帮助都将不胜感激!

感谢

例如,要处理if $words[$i] exist, print it, else reset the array,我会使用更整洁的$i % count($array)

$array = array(
    '0' => 'This',
    '1' => 'is',
    '2' => 'my',
    '3' => 'word'
);
for ($i = 0; $i < 6; $i++) {
    echo $array[$i % count($array)] . ' ';
}
// "This is my word This is "

或者,如果你想要问题中指定的确切输出(末尾没有空格(,我可能会做

$string = '';
for ($i = 0; $i < 6; $i++) {
    $string .= $array[$i % count($array)] . ' ';
}
echo trim($string);
// "This is my word This is"

或者类似的东西

echo $array[$i % count($array)] . ($i == 5 ? null : ' ');
// "This is my word This is"

试试这个:

$words       = array('first', 'second', 'third');
$result      = '';
$index       = 0;
$words_count = count($words);
for ($i = 0; $i < 5; ++$i) {
    $result .= ' ' . $words[$index];
    ++$index;
    if ($index >= $words_count) {
        $index = 0;
    }
}
die(var_dump($result));

不需要第二个变量进行迭代的最优雅的解决方案可能是使用模运算符:

for ($i=0; $i < NUMBER_OF_WORDS ; $i++) { 
    echo $words[$i % count($words)] . ' ';
}

这将$words数组的echoNUMBER_OF_WORDS个字,并在使用完数组的所有字后再次从索引0开始。

您的数组定义错误,开头为:

$words = array (
  0 => 'This',
  1 => 'is',
  2 => 'my',
  3 => 'word'
);

现在要打印它,你可以做:

for ($i=0; $i < 6 ; $i++) {
  if(isset($words[$i])) { echo $words[$i] . ' '; }
}

对于您更奇怪的要求:

for ($i=0; $i < 6; $i++) { 
    echo $words[$i % count($words)], ' ';
}

试试这样的东西:

$n = 0;
for ($i=0; $i < 6 ; $i++) { 
    echo $words[$n];
    $n++;
    if($n == count($words){
        $n -= count($words);
    }
}

如果你到达数组的末尾,它会将$n重置为零;

for($i=0; $i<6; $i++) {
  if($i >= sizeOf($words)) {
    echo $words[$i % sizeOf($words)];
  }
  else { echo $words[$i]; }
}

应该做这个把戏。

试试这个:

for ($i=0; $i < 6 ; $i++) { 
    echo $words[$i%(sizeof($words))];
}
for ($i = 0; $i < 6 ; $i++) {
    if(!empty($words[$i])) 
        echo $words[$i];
    else
        for($j = 0 ; $j <= $i; $j++){
            echo $words[$j];
        }
}