简体   繁体   English

计算以“custom_”开头的 $_POST 回复

[英]Count $_POST reply starting by "custom_"

On my website, we can create a product with an unknown number of custom field.在我的网站上,我们可以创建一个自定义字段数量未知的产品。 To insert my data inside the database, I want to know the number of inputs starting with "parameter" (in my data below).要将我的数据插入数据库中,我想知道以“参数”开头的输入数量(在下面的数据中)。

How can I count() the POST result starting with "parameter"?如何计算()以“参数”开头的 POST 结果? Thanks谢谢

array(6) {
    ["quantity"]=> string(8) "200"
    ["price"]=> string(4) "150"
    ["product_supplier"]=> string(4) "1"
    ["parameter1"]=> string(4) "text"
    ["parameter2"]=> string(7) "Exemple"
    ["parameter3"]=> string(4) "text"
}

Use array_keys to get the keys of the array, and then iterate through using a foreach or array_reduce eg使用array_keys获取数组的键,然后使用foreacharray_reduce进行迭代,例如

$count = 0;
foreach (array_keys($array) as $key) {
    if (strpos($key, 'parameter') === 0) $count++;
}
echo "$count parameters\n";

$count = array_reduce(array_keys($array), function ($c, $v) { 
    if (strpos($v, 'parameter') === 0) $c++; 
    return $c; },
    0);
echo "$count parameters\n";

Output (for your sample data):输出(对于您的示例数据):

3 parameters

Demo on 3v4l.org 3v4l.org 上的演示

You might instead want to consider naming your parameter inputs using PHP's array notation eg您可能想考虑使用 PHP 的数组符号命名参数输入,例如

<input type="text" name="parameters[]" />

Then all your parameter inputs will appear as an array in $_POST['parameters'] and you can get the count easily via然后您所有的参数输入将显示为$_POST['parameters']的数组,您可以通过以下方式轻松获取计数

echo count($_POST['parameters']);

It will probably make it easier to process the parameters too as you can use a simple foreach :它可能会使处理参数变得更容易,因为您可以使用简单的foreach

foreach ($_POST['parameters'] as $parameter) {
    // do stuff
}

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

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