如何在PHP中设置选定的值?

时间:2014-02-08 10:40:34

标签: php

我制作一个php页面,其中我发布数据我想要的时候发布数据等于选项值然后选项值显示选中,这是我的帖子数据:

Array (
    [events]       => Array 
    [fromdate]     => February 12, 2014 3:10 PM 
    [todate]       => February 19, 2014 3:10 PM 
    [description]  => hfhhhhhhhhhhhhhhhhhh 
    [subject]      => fhhhhhhhhhhhhhhhhhh 
    [fromname]     => gjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj 
    [replyto]      => gjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj 
    [senddatetime] => February 12, 2014 3:10 PM 
    [timezone]     => America/Los_Angeles 
    [message]      =>

                 dhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
    [submit_skip]  => Continue 
) 

这是我的代码:

            

        $select = sprintf ("SELECT event_id,event_name
                              FROM `events`
                              WHERE (`user_id` = '%s') order by event_name",
                            $GLOBALS ['mysqli']->real_escape_string ($_SESSION['user_id']));

        $res = $GLOBALS ['mysqli']->query ($select) or die ($GLOBALS ['mysqli']->error . __LINE__);
        if ($res->num_rows > 0)
        {                   
            while($row = $res->fetch_assoc ())
            {
                foreach( $_POST['events'] as $val ){ ?>

                     <option value="<?= $row['event_id']; 
                         if($row['event_id'] == $val) echo "selected";
                     ?>">
                         <?=$row['event_name']?>
                     </option>

                     <?
                 }
             }
        }
        ?>
        </select>

我想要[events] =&gt;在选择选项中检查数组,如果事件值匹配,选择框显示已选中,我该怎么做?

当我运行此错误时显示:

Warning:  Invalid argument supplied for foreach() in C:\wamp\www\ticket_inspector_new\forms_hd87wblfo084wgdtry\form_email_compose

1 个答案:

答案 0 :(得分:1)

首先单独创建事件数组,然后应用它,就像这样

    <?php
    $x = array (
        'events'       => array(), 
        'fromdate'     => 'February 12, 2014 3:10 PM', 
        'todate'       => 'February 19, 2014 3:10 PM', 
       // So on .....
    ); 

    $check = $x['events'];

    var_dump($check);

    ?>

            <option value="<?php echo $row['event_id']; ?>"<?php if(in_array($row['event_id'],$check)) { ?> selected="selected" <?php } ?> ><?php echo $row['event_name']?></option>