Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 仅处理以特定字符串开头的$\u POST元素_Php_Html_Arrays_Forms_Post - Fatal编程技术网

Php 仅处理以特定字符串开头的$\u POST元素

Php 仅处理以特定字符串开头的$\u POST元素,php,html,arrays,forms,post,Php,Html,Arrays,Forms,Post,我正在处理一个表单,它将通过$\u POST接收大量元素。其中一定数量(太大,无法手动写出)遵循以下模式: $_POST['city_1'] $_POST['city_2'] $_POST['city_3'] $_POST['city_4'] 等等 表单的设置方式,我不确定有多少像这样的元素会被发送过来——可能是一个,也可能是50个。如何根据$u POST元素的名称处理其中的几个元素?您可以像数组一样循环处理$u POST foreach($_POST as $key=>$value)

我正在处理一个表单,它将通过$\u POST接收大量元素。其中一定数量(太大,无法手动写出)遵循以下模式:

$_POST['city_1']
$_POST['city_2']
$_POST['city_3']
$_POST['city_4']
等等


表单的设置方式,我不确定有多少像这样的元素会被发送过来——可能是一个,也可能是50个。如何根据$u POST元素的名称处理其中的几个元素?

您可以像数组一样循环处理$u POST

foreach($_POST as $key=>$value) {
  //filter based on $key
}

您应该创建一个多维数组

您的HTML表单字段可能如下所示:

<input type="text" name="cities[city_1]">
<input type="text" name="cities[city_2]">
<input type="text" name="cities[city_3]">
<input type="text" name="cities[city_4]">


`foreach`遍历数组的所有元素。然后检查是否满足要求

foreach($_POST as $key => $value)
    if(preg_match("/^city_\d+$/", $key))
        ...
$cities = preg_grep('/^city_\d+$/', array_keys($_POST));

foreach($cities as $city) {
    echo $_POST[$city];
}
foreach($_POST as $name=>$value) {
    if (strpos($value, 'city_') !== 0) continue;

    echo $value;
}
foreach($_POST as $key => $value)
    if(preg_match("/^city_\d+$/", $key))
        ...
function startsWith($haystack, $needle)
{
  $length = strlen($needle);
  return (substr($haystack, 0, $length) === $needle);
}


foreach ($_POST as $k=>$v)
{
  if (startsWith($k, 'city_')
  {
    // Process parameter here ...
  }
}