PROBLEM
I have a nested PHP array that I need to populate from flat scalar
values. The problem is I cannot know ahead of time what the structure
of the nested PHP array will be until I get the request to fill in
the flat scalar values.
EXAMPLE
// example where we populate the array using standard PHP
$person['contact_info']['fname'] = 'Attilla';
$person['contact_info']['lname'] = 'Hun';
$person['contact_info']['middle'] = 'The';
$person['hobbies'][0] = 'Looting';
$person['hobbies'][1] = 'Pillaging';
// example where we populate the array from flat scalar values
// (these are obtained from the user via name-value pairs)
// how can I correctly populate $person from this??
print($_GET['contact_info.fname']); // 'Smokey';
print($_GET['contact_info.middle']); // 'The';
print($_GET['contact_info.lname']); // 'Bear';
// how can I correctly populate $person from this??
print($_GET['contact_info.fname']); // 'Jabba';
print($_GET['contact_info.middle']); // 'The';
print($_GET['contact_info.lname']); // 'Hutt';
// How can I use these three flat scalars
// to populate the correct slots in the nested array?
QUESTION
I know I must not be the first person who has needed to convert from flat name-value pairs into a nested PHP array (or nested array in any programming language). What is the established way (if any) of converting these flat scalar name-value pairs into the appropriate PHP nested array?
Just to re-iterate, I cannot know ahead of time what the name-value pairs will be for populating the array, that is one constraint I am dealing with here.
UPDATE
The fact that I cannot know the values (or, if you prefer, the Array keys that get populated by the scalar-value-representations) is a constraint of the particular problem space I am dealing with. This is not a question about basic PHP array syntax.
Note: My PHP code below is a hack, instead do this. Someone had posted a better solution earlier, but the post is gone now. In short, you can already submit arrays of values in forms to PHP:
The square brackets in the name attribute do exactly what you think they might do. On submit,
$_POST['contact_info']will be an array with three keys,fname,lname, andmiddle.If at all possible, you should use this method rather than the code I’ve written below. It’s cleaner, it’s better, it’s more maintainable, it’s the way it should be done.
This is a fun challenge. We’re going to use PHP’s funny way of doing references to our advantage. Given that:
Then this function might be a starting point for you.
Again, this is a hack. You should use PHP form handling to take care of this for you.