Question

I'm trying to take a multidimensional array and convert it into HTML form fields, like this:

<input type="hidden" name="c_record[contact][0][name]" value="First Last">
<input type="hidden" name="c_record[contact][0][date_submitted][date]" value="2010-01-01">
<input type="hidden" name="c_record[contact][0][date_submitted][hour]" value="10">
<input type="hidden" name="c_record[contact][0][date_submitted][min]" value="08">
<input type="hidden" name="c_record[contact][0][date_submitted][sec]" value="16">
<input type="hidden" name="c_record[contact][0][ip_address]" value="192.168.1.1">

Here is what I have so far:

$fields = array(
    'c_record' => array(
        'contact' => array(
            0 => array(
                'name' => 'First Last',
                'date_submitted' => array(
                    'date' => '2010-01-01',
                    'hour' => '10',
                    'min' => '08',
                    'sec' => '16',
                ),
                'ip_address' => '192.168.1.1',
            ),
        ),
    ),
);
$form_html = array_to_fields($fields);

function array_to_fields($fields, $prefix = '') {
    $form_html = '';

    foreach ($fields as $name => $value) {
        if ( ! is_array($value)) {
            if ( ! empty($prefix)) {
                $name = $prefix . '[' . $name . ']';
            }
            // generate the hidden field
            $form_html .= Form::hidden($name, $value) . EOL;
        } else {
            if ( ! empty($prefix)) {
                $prefix .= '[' . $name . ']';
            } else {
                $prefix = $name;
            }
            $form_html .= array_to_fields($value, $prefix);
        }
    }

    return $form_html;
}

This works fine until ip_address, which results in:

<input type="hidden" name="c_record[contact][0][date_submitted][ip_address]" value="192.168.1.1">

And any additional fields after ip_address keep having the previous field names added to them.

How can I make this work?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top