in_array的选项值不起作用

时间:2018-08-01 05:19:49

标签: php arrays drop-down-menu

我有

$this->getcoursebyid[0]['p_id']=2,4

$ this-> getprofile

Array
    (
        [0] => Array
            (
                [profile_id] => 1
                [profile_name] => Administrator
                [profile_type] => GLOBAL
                [profile_tag] => ADM
                [profile_default] => 0
            )

    [1] => Array
        (
            [profile_id] => 2
            [profile_name] => Product Owner
            [profile_type] => GLOBAL
            [profile_tag] => PO
            [profile_default] => 0
        )

    [2] => Array
        (
            [profile_id] => 3
            [profile_name] => Team member
            [profile_type] => GLOBAL
            [profile_tag] => MEMBER
            [profile_default] => 0
        )

    [3] => Array
        (
            [profile_id] => 4
            [profile_name] => Tester
            [profile_type] => GLOBAL
            [profile_tag] => TES
            [profile_default] => 0
        )

)

我想从选项值中选择$this->getcoursebyid[0]['p_id'],所以我做了以下事情

$proid=explode(',',$this->getcoursebyid[0]['p_id']);

<select name="framework[]" multiple id="framework" class="form-control" >
    <?php
      $i=0;
       foreach ($this->getprofile as $getprofile):                                                       
    ?>                         
    <option value="<?php echo $getprofile['profile_id'] ?>"<?php if(in_array($proid[$i],$getprofile)){ ?>selected="selected"<?php } ?>><?php echo $getprofile['profile_name'] ?>_<?php echo $i; ?></option>
    <?php $i++; endforeach; ?>
  </select>

但这无法正常工作..我没有得到正确的值。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您正在迭代$ this-> getprofile并在$ proid [$ i]中分配其索引,但是$ proid仅具有两个索引array(0 => 2,1 => 4)所以显然它将给您错误

<select name="framework[]" multiple id="framework" class="form-control" >
 <?php
   $i=0;
   foreach ($this->getprofile as $getprofile):
   ?>                         
   <option value="<?php echo $getprofile['profile_id'] ?>"<?php if(in_array($proid[$i],$getprofile)){ ?>selected="selected"<?php } ?>><?php echo $getprofile['profile_name'] ?>_<?php echo $i; ?></option>
    <?php $i++; endforeach; ?>
   </select>

您应该阅读in_array手册

in_array(needle, haystack)

下面是解决方法。

<select name="framework[]" multiple id="framework" class="form-control" >
 <?php
   $i=0;
   foreach ($this->getprofile as $getprofile):
  ?>                         
   <option value="<?php echo $getprofile['profile_id'] ?>"<?php if(in_array($getprofile['profile_id'],$proid)){ ?>selected="selected"<?php } ?>><?php echo $getprofile['profile_name'] ?>_<?php echo $i; ?></option>
   <?php $i++; endforeach; ?>

                                    </select>