【问题标题】:GET input as PHP array将输入作为 PHP 数组获取
【发布时间】:2021-12-15 11:04:46
【问题描述】:

我的 HTML 输入为

<input type="number" name="no_pi" id="no_pi" class="form-control" placeholder="Number of Pieces">

其他两个输入为

<input type="number" name="ht" id="ht" placeholder="Height of Package" class="form-control">
<input type="number" name="bd" id="bd" placeholder="Breadth of Package" class="form-control">

我想在件数字段中输入3,然后在重量字段中输入20, 20, 30,在宽度字段中输入10, 10, 20

PHP 将计算每个20, 10 和下一个对,依此类推x 在件数字段中分配的次数。

PS:上面定义的数组是一个例子,如果用户输入 5 个片段,那么两个数组都应该是 5 个值,PHP 将对这 5 对进行计算。

知道如何实现这一目标

【问题讨论】:

    标签: php html forms


    【解决方案1】:

    您可以使用explodearray_map 来实现此目的。

    function inputToArray(string $string)
    {
        $string = preg_replace('/\s+/', '', $string);
        $string = trim($string, ",");
        $array = array_map('intval', explode(',', $string));
        return $array;
    }
    
    $no_of_pieces = (int)$_POST['no_pi'];
    $ht = $_POST['ht']; //make sure it is in format 1,2,3,4,.....
    $ht = inputToArray($ht); //array(20,30,10)
    $bd = $_POST['bd']; //make sure it is in format 1,2,3,4,.....
    $bd = inputToArray($bd); // array(10,20,30)
    
    if ((count($ht) === count($bd)) && (count($bd) === $no_of_pieces)) {
        for ($piece = 0; $piece < $no_of_pieces; $piece++) {
            $areaOfPiece = $ht[$piece] * $bd[$piece];
            echo $areaOfPiece;
        }
    } else {
        echo "Number of inputs does not match";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-19
      • 2010-10-24
      • 1970-01-01
      • 2015-03-24
      • 2013-12-09
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      相关资源
      最近更新 更多