繁体   English   中英

PHP获取带值的数组键

[英]PHP Get Array key with Value

我正在尝试获取每个具有值的输入类型的数组键。

请看下面我的代码

<form action="welcome.php" method="post">
<input type="text" name="ptotal_monthly_fee[]" >
<input type="text" name="ptotal_monthly_fee[]" value"1">
<input type="text" name="ptotal_monthly_fee[]" >
<input type="text" name="ptotal_monthly_fee[]" value"2">
<input type="text" name="ptotal_monthly_fee[]" >
<input type="submit">

</form>

这是welcome.php

<?php

$count = array_keys($_POST['ptotal_monthly_fee']);

foreach ($count as $value) {
  echo "$value <br>";
}
?>

我的输出是:0 1 2 3 4

我希望我的输出是:1 3

您需要检查posted数组中的值,如果值不为空,则回显相应的键:

foreach ($_POST['ptotal_monthly_fee'] as $key => $value) {
    if (!empty($value)) echo "$key <br>";
}
$stmt = '';
if(isset($_POST['ptotal_monthly_fee'])){
  foreach($_POST['ptotal_monthly_fee'] as $key => $value){
    if($value !== ''){
      $stmt .= "Key: $key<br>";
    }    
  }
}

在 html 中回显 $stmt

<?=$stmt?>

注意:在您的代码中,您的输入中未设置您的值。 应该是value="1" / value="3"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM