在PHP中循环序列化表单字段

时间:2014-08-10 12:01:07

标签: javascript php jquery forms

我收到一个PHP函数的序列化字符串(通过Ajax发送到PHP)。让我们说它看起来像这样:

year=1923&season=Winter&person_1_name=barry&person_1_age=20&person_2_name=Tom&person_3_name=Jane&person_3_age=30

我需要知道在PHP中如何将这些编号字段拆分出来,以便我可以用它们做点什么,例如:

foreach ( person_x as person ) {
    // do something here with person_x's details
}

此外,我无法概括我将收到的信息,因为有些人可能没有所有信息(注意person_2在上面的示例中没有年龄)并且这些字段中将存在未知数量(它们可重复使用形式)

1 个答案:

答案 0 :(得分:2)

使用parse_str() 推荐方法

$string = 'year=1923&season=Winter&person_1_name=barry&person_1_age=20&person_2_name=Tom&person_3_name=Jane&person_3_age=30';

parse_str($string, $output);
foreach ($output as $key => $person){
 echo $key  . " = " . $person . "<br />";
}

使用explode()

$string = 'year=1923&season=Winter&person_1_name=barry&person_1_age=20&person_2_name=Tom&person_3_name=Jane&person_3_age=30';

$persons = explode("&", $string);    
foreach ($persons as $person){
  $details = explode("=", $person); 
  echo $details[0] . " = " . $details[1] . "<br />";
}

输出:

year = 1923
season = Winter
person_1_name = barry
person_1_age = 20
person_2_name = Tom
person_3_name = Jane
person_3_age = 30
----------
year = 1923
season = Winter
person_1_name = barry
person_1_age = 20
person_2_name = Tom
person_3_name = Jane
person_3_age = 30

排除所有其他不以person_

开头的字段
parse_str($string, $output);
foreach ($output as $key => $person){
 if(preg_match('/person_/', $key)){
   echo $key  . " = " . $person . "<br />";
 }
}

输出:

person_1_name = barry
person_1_age = 20
person_2_name = Tom
person_3_name = Jane
person_3_age = 30