如何获取 PHP 中 select 列表中的选项数

How can I get the count of options in a select list in PHP

我在 Javascript 中有条件填充的选项。在 php 中,我需要获取特定 select 框的选项数,然后根据选项数执行一个函数。

另一个想法是将选项值放在一个数组中?

我试图避免 Javascript 或 jQuery,因为我必须将此信息传递给 twig 文件以显示 div 并向用户显示说明,如果没有的话出现在列表中。

HTML

     <select id="cars" name="cars">
        <option val="honda">Honda</option>
        <option val="nissan">Nissan</option>
        <option val="toyota">Toyota</option>
     </select>

PHP

    foreach ($_GET['cars'] as $item)
    {
        var noOfCars = count($item);
        if ($noOfCars == 3){
            //do something
        }   
    }

虽然你用JS动态生成你的select的选项,你也应该用JS计算它,然后你需要将选项的数量放入隐藏字段,以便发送:


<form action="script.php" method="post">
    <select name="cars" id="cars">
        <option value="toyota">Toyota</option>
        <option value="audi">Audi</option>
        <option value="bmw">BMW</option>
    </select>
    <input type="hidden" name="car_options_count" id="carOptionsCount" value="0">
    <input type="hidden" name="car_options" id="carOptions" value="0">
    <input type="submit" value="Send the form">
</form>

<script>
    // populate additional options
    let $cars = jQuery('#cars');
    $cars.append(new Option('Opel', 'opel'));
    $cars.append(new Option('Honda', 'honda'));

    // some time later... count options in your select and set the value in hidden form's field
    let $options = jQuery('#cars option');
    jQuery('#carOptionsCount').val($options.length);

    // You can even send these dynamic options the same way as a JSON stringified object
    let optArray = [];
    $options.each(function () {
        let $el = jQuery(this);
        optArray.push([$el.val(), $el.text()])

    })
    jQuery('#carOptions').val(JSON.stringify(optArray))
</script>

并在 PHP 脚本中从 $_POST 数组中读取它:

<?php

// validation of input data skipped, but should be done here
echo "You have {$_POST['car_options_count']} options available in your form, and selected exactly: '{$_POST['cars']}' option <br>";

$options = json_decode($_POST['car_options'], true);
var_dump($options);