【问题标题】:Only process $_POST elements that begin with a certain string仅处理以某个字符串开头的 $_POST 元素
【发布时间】:2012-01-17 14:37:15
【问题描述】:
我正在处理一个将通过 $_POST 接收大量元素的表单。其中某些数量(太大而无法手动写出)遵循某种模式:
$_POST['city_1']
$_POST['city_2']
$_POST['city_3']
$_POST['city_4']
等等
表单的设置方式,我不确定要发送多少这样的元素——可能是一个,也可能是 50。我怎样才能只处理几个 $_POST 元素根据他们的名字?
【问题讨论】:
标签:
php
html
arrays
forms
post
【解决方案1】:
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 ...
}
}
【解决方案2】:
´foreach` 遍历数组的所有元素。然后检查是否满足要求。
foreach($_POST as $key => $value)
if(preg_match("/^city_\d+$/", $key))
...
【解决方案3】:
$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;
}
【解决方案4】:
您应该创建一个多维数组。
您的 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]">
在您的 PHP 代码中,您可以通过访问 $_POST['cities'] 来遍历您的城市:
foreach($_POST['cities'] as $city)
{
echo $city;
}
【解决方案5】:
您可以像数组一样循环遍历 $_POST。
foreach($_POST as $key=>$value) {
//filter based on $key
}