簡體   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