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 vc6.0中想运行代码的时候总是提示无法打开文件是怎么回事
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题