Question:
I have an array of post values that looks like:
$_POST['children'] = array(
[0]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
),
[1]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
),
[2]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
)
);
// and so on
I have a script set up in my my view functions that checks for old input, and repopulates the values in the case that the form does not validate. I need to find a way to return the above array as a series of key/value pairs i.e.
'children[0][fname]' = 'name'
'children[0][mname]' = 'mname'
'children[0][lname]' = 'lname'
// ... and so on for all fields
Ideally, I would like this to work with an array of any depth, which makes me think I need some sort of recursive function to format the keys. I am having a terrible time getting my head around how to do this.
What I have tried
I have been working with the following function:
function flatten($post_data, $prefix = '') {
$result = array();
foreach($post_data as $key => $value) {
if(is_array($value)) {
if($prefix == ''){
$result = $result + flatten($value, $prefix. $key );
}else{
$result = $result + flatten($value, $prefix. '[' . $key . ']');
}
}
else {
$result[$prefix . $key .''] = $value;
}
}
return $result;
}
This gets me somewhat close, but isn't quite right. It returns the following when I feed it my $_POST array
[children[1]fname] => test
[children[1]mname] => test
[children[1]lname] => test
[children[1]dob] =>
// Expecting: children[1][fname] => test
// ...
Or is there potentially an easier way to accomplish this?