从用户输入循环遍历数组

时间:2015-03-20 14:35:56

标签: php arrays loops

我有一个带有选择字段的表单,该字段包含星期几,我已经有数组中的日期

$weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

我正在使用

填充选择
<select name="weekday">
                    <?php
                    foreach ($weekdays AS $weekday) {
                        PRINT '<option value="' . $weekday . '">' . $weekday . '</option>';
                    }
                    ?>
                </select>

我现在正在尝试创建一个响应页面,它将在选定的一个后打印出接下来的三个星期,但我不确定如何,我目前只有

$weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
foreach($weekdays as $value){ 
    echo $value . "<br />\n";

我知道我必须从表单中收集用户输入的值,但是一旦我拥有它就不知道我做了什么,例如

$weekday = $_POST['weekday'];

3 个答案:

答案 0 :(得分:0)

使用array_keys查找要解析的下一个值的键,并检查是否要将解析重置为星期一:

$receivedDay = 'Saturday';
$weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

for ($i = 1; $i < 4; $i++) {
  $key = array_keys($weekdays, $receivedDay);
  $key = $i + $key[0];
  if ($key > 6) {
    $key -= 7;
  }
  echo $weekdays[$key] . PHP_EOL; // Or <br>
}

输出

Sunday
Monday
Tuesday

答案 1 :(得分:0)

这应该是你的PHP代码 以这种方式改变前端

<select name="weekday">
                    <?php
                    foreach ($weekdays AS $weekdayKey=>$weekdayValue) {
                        PRINT '<option value="' . $weekdayKey . '">' . $weekdayValue . '</option>';
                    }
                    ?>
                </select>

这里有5代表星期六从前端发送索引

 <?php 
    $array = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
    $total = count($array);
    $sel =5;
    for($i=0;$i<3;$i++) {
        $sel = $sel+1;
        if($sel>=$total){
            $sel = $sel-$total;
        }
        $getDays [] = $array[$sel];
     }
     echo "<pre>";
        print_r($getDays);
     echo "</pre>"; 
    ?>

答案 2 :(得分:0)

第一步是将您的选择放在<form>

<form action="request.php">
   <select name="weeks">
         foreach here
   </select>
</form>

将内容放在新文件request.php内的同一文件夹

<?php
    $weekName = $_REQUEST['weekday'];
    // Your logic about $weekName
    echo $weekName;
?>