Scott L
Scott L

Reputation: 549

Loop Serialised Form Fields in PHP

I am receiving a serialized string into a PHP function (sent via Ajax to PHP). Let's say it looks like this:

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

I need to know how in PHP to split those numbered fields out so I can do something with them, like:

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

Also I can't generalise the information I will receive as some may not have all the info (note person_2 does not have an age in the above example) and there will be an unknown number of these fields (they are repeatable in the form)

Upvotes: 1

Views: 63

Answers (1)

hex494D49
hex494D49

Reputation: 9245

Using parse_str() Recommended method

$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 />";
}

Using 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 />";
}

Output:

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

Exclude all other fields that don't start with person_

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

Output:

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

Upvotes: 2

Related Questions