douhuanqiao5290 2014-05-22 02:06
浏览 24
已采纳

如果数组echo键中存在post数据

I have an input with this form action:

<?php
  $product_add = $_POST['product'];
  $pa = strtolower($product_add);
  $tv= array('Sony'=>'sony tv', 'vizio' => 'vizio tv', 'panasonic' => 'panasonic tv');
  if (in_array($pa, $tv)) {
    foreach ($tv as $key => $item) {
      if ($item === $pa) {echo $item.' is begin with ('.$key.')';}
    }
?>
<div class="tv">
  <form name="addform" action="inc/ap-tv.inc.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="product_type" value="TV">
    <input type="hidden" name="user" value="<?php echo $_SESSION['user_name'] ?>">  
    <label for="brand">Brand</label> <input type="text" name="brand" value="<?php echo $key; ?>"><br>
    <input name="" type="submit" value="Add Television" />
  </form>   
</div>
<?php
}
?>

If someone enters 'Sony TV' into the initial input form I want the word "Sony" to appear as the value in the brand field.

When I echo $key in the foreach loop it works but when I try to echo it as the input value I get a number. how can I make the variable useable outside of the foreach loop? I've also tried using both 'print' and 'print_r()' but neither work. Sorry if this is simple, I'm kind of a beginner with this stuff.

Thanks!

  • 写回答

3条回答 默认 最新

  • doukun5339 2014-05-22 02:15
    关注

    $key only exists inside of your loop. When the loop terminates, the variables declared by it do, too.

    All you need to do is use array_search() to get the key based on the value:

    if (in_array($pa, $tv)) {
        $brand = array_search(strtolower($pa), $tv);
    }
    
    <label for="brand">Brand</label> 
    <input type="text" name="brand" value="<?php echo $brand; ?>"><br>
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用