Anyone doing web development requiring client-server interaction is familiar with GET and POST. (There are others as well, including PUT, DELETE, and so on. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html for the list.) And pretty quickly most folks become aware of the ability to pass arrays as request parameters. For example:
<form method="post" action="http://www.example.com/myformproc.php">
<fieldset>
<legend>Notification Methods<legend>
<input type="checkbox" name="note_opts[]" value="email" id="note_opt_email"><label for="note_opt_email">E-Mail</label>
<input type="checkbox" name="note_opts[]" value="text" id="note_opt_text"><label for="note_opt_text">Text Message</label>
... etc ...
</fieldset>
</form>
On the server side, if the user selected any of the notification options, you would have an array in a POST variable, ‘note_opts’. In PHP, for example you would see an array $_POST['note_opts']. That array would contain the values of the selected options. The indexes of those values would be numerically indexed in the usual, default, manner.
What if we’re editing the options for multiple objects. Each of our objects has an id number and 0 or more of the options.
What I often see is:
<input type="checkbox" name="obj_<?php echo $object->getID(); ?>_note_opts[]" value="email" id="note_opt_email">
And then we end up having to parse the id out of the variable name…
Far better to do something like:
<input type="checkbox" name="note_opts[<?php echo $object->getID(); ?>][]" value="email" id="note_opt_email">
In this way we get a 2 dimensional array of note_opts. The object with id ’1′ is simply $_POST['note_opts'][1].
This also makes it easy to loop through the objects getting their ids along the way
$note_opts = $_POST['note_opts'];
if (is_array($note_opts)) {
foreach($note_opts as $obj_id=>$opt_set) {
$obj = MyType::get($obj_id);
if (!$obj) {
addError("Failed to get object (".$obj_id.")";);
} elseif (!$obj->setOptions($opt_set)) {
addError("Failed to set options for ".$obj->getName()." (".$obj_id.")";);
}
}
}
It’s not a big leap from note_opts[] to note_opts[2][email_options][address]. Organizationally it makes life a lot easier, especially if there is any complexity to your data. This way hierarchical data can easily be represented in nested arrays. One final comment, please note that the named array indices like email_options and address are not enclosed in quotes.