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条)

报告相同问题?