drtiwd06558 2016-01-04 21:12 采纳率: 100%
浏览 68
已采纳

我如何进一步在这个php数组1索引中放置元素?

I have to make a little script for a school assignment which places the days of the week in chronological order with an index in front of them. Although Sunday has to be the first day and therefore must have the number 1 in front of it. (2 Monday, 3 Tuesday etc.)

I have tried to do this by placing all the elements in the array one index further but it does not seem to work.

$myArray = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
for ($i=0; $i<count($myArray); $i++) {
  $myArray[$i] = $myArray[$i+1];
  echo ($i+1) . " " . $myArray[$i] . "<br>";
}

And here is the error message i get when i execute the code:

1 Tuesday
2 Wednesday
3 Thursday
4 Friday
5 Saturday
6 Sunday

Notice: Undefined offset: 7 in C:\xampp\htdocs\opdracht_22.php on line 13
7

The result i am trying to get is:

1 Sunday
2 Monday
3 Tuesday
4 Wednesday
5 Thursday
6 Friday
7 Saturday

Is there anything i am missing here? How can i improve my code?

  • 写回答

4条回答 默认 最新

  • doutu1939 2016-01-04 21:29
    关注

    You can achieve the desired result using simple while loop,

    <?php
        $myArray = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
        $array_length = count($myArray);  // $array_length is 7
        $index = $array_length - 1;  // $index is 6 here 
        $counter = 1;  // here $counter is used to print Nth weekday
        while(true){
            echo $counter . " " . $myArray[$index] . "<br />";
            $index = ($index + 1) % $array_length;  // performs increment and modulus operation to get the reminder value
            ++$counter;
            if($index == $array_length - 1){  // whenever $index is 6 again the loop will terminate
                break;
            }
        }
    ?>
    

    Output:

    1 Sunday
    2 Monday
    3 Tuesday
    4 Wednesday
    5 Thursday
    6 Friday
    7 Saturday
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

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