2011-12-10 23 views
2

我正在处理一个表单,它将通过$ _POST接收大量元素。这些一定数量的(得大一些手工写出来)遵循这样一个规律:

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

形式设立的方式,我不知道有多少元素像这样将会被发送 - 它可能是一个,它可能是50.如何根据它们的名字处理$ _POST元素中的几个?

回答

3

您应该改为创建一个多维数组。

你的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; 
} 
+0

http://www.php.net/manual/en/faq.html.php#faq.html.arrays – goat

+0

啊我是不是开了这个!非常感谢。这简化了很多... – delwin

0

您可以像数组一样循环$ _POST。

foreach($_POST as $key=>$value) { 
    //filter based on $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; 
} 
1

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

foreach($_POST as $key => $value) 
    if(preg_match("/^city_\d+$/", $key)) 
     ... 
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 ... 
    } 
} 
相关问题