Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sleavely/2c1aa7ba13da80dfeb43 to your computer and use it in GitHub Desktop.
Save Sleavely/2c1aa7ba13da80dfeb43 to your computer and use it in GitHub Desktop.
Dealing with dynamic amounts of fields in HTML forms usually means you get your data in a very foreach-unfriendly manner. This helper function is meant to address that. Input and output are presented in JSON because I like it better. Actual results are PHP. YMMV
<?php
/**
* Helper function to reformat arrays.
* @see https://gist.github.com/Sleavely/2c1aa7ba13da80dfeb43
*
* @param array $source
* The multidimensional array where each input field is an array
* @param array $arrays
* A list of which keys to include in the output
* @return array
* An array where each entry represents an object (e.g. an attendant).
*/
function arrayFromHTMLInput($source, $arrays)
{
$output = array();
foreach($arrays as $field)
{
if(isset($source[$field]) && is_array($source[$field]))
{
foreach($source[$field] as $i => $value)
{
if(!isset($output[$i]))
{
$output[$i] = array();
}
$output[$i][$field] = $value;
}
}
}
return $output;
}
<?php
$input = json_decode(file_get_contents('input.json'));
require_once('arrayFromHTMLInput.php');
// This will produce the same kind of output as output.json
$output = arrayFromHTMLInput(
$input,
array('firstname', 'lastname', 'email', 'phone')
);
{
"firstname":[
"John",
"Eric",
"Alex"
],
"lastname":[
"Johnson",
"Ericsson",
"Andersen"
],
"email":[
"john@example.com",
"eric@example.com",
"alex@example.com"
],
"phone":[
"555-123 123 1",
"555-123 123 2",
"555-123 123 3"
],
"someRandomData":"XYZ",
"moreRandomData":1337
}
[
{
"firstname":"John",
"lastname":"Johnson",
"email":"john@example.com",
"phone":"555-123 123 1"
},
{
"firstname":"Eric",
"lastname":"Ericsson",
"email":"eric@example.com",
"phone":"555-123 123 2"
},
{
"firstname":"Alex",
"lastname":"Andersen",
"email":"alex@example.com",
"phone":"555-123 123 3"
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment