php - Converting a multi-dimensional array into HTML form fields - how? -


i'm trying take multidimensional array , convert html form fields, 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 have 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 $name => $value) {         if ( ! is_array($value)) {             if ( ! empty($prefix)) {                 $name = $prefix . '[' . $name . ']';             }             // generate 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, results in:

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

and additional fields after ip_address keep having previous field names added them.

how can make work?

you manhandle http_build_query service purpose, since naturally creates scrunched-together keys you're looking for. if wait until end urldecode keys , values, it's easy explode output, since = or & in key or value safely encoded.

function array_to_fields($array) {     $html = '';      $entries = explode('&', http_build_query($array));     foreach ($entries $entry) {         list($key, $value) = explode('=', $entry);         $html .= form::hidden(urldecode($key), urldecode($value)) . eol;     }      return $html; } 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -