doufocheng6233 2014-07-22 10:20
浏览 25
已采纳

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

I have an array with a random number of words. It can contain a single word as a minimum or more than 10 words. Example:

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

Now, lets say i want to echo out 6 words from this array, starting over when we reach the end of the array. I want the logic to be something like this

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

I'd like the result to be: "This is my word this is"

I struggle to figure out the maths for this. Any help would be much appreciated!

Thanks

  • 写回答

8条回答 默认 最新

  • duansao6776 2014-07-22 10:30
    关注

    To handle if $words[$i] exist, print it, else reset the array I'd use something neater $i % count($array), for example.

    $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 "
    

    Or if you wanted your exact output as specified in your question, (no spaces on the end), I'd probably do

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

    or alternatively something like

    echo $array[$i % count($array)] . ($i == 5 ? null : ' ');
    
    // "This is my word This is"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀