lets say i have this nested array: $this_guy = array( "name"=>"a guy", "address"=>array( "street" => "s. mile", "zip"=>"123", "city"=>"mooflake town") "email"=>"spam@hotmail.com"); PHP: now how can i make a form out of this array (some smart function maybe)? i want to be able to edit this array, and i already have some function to display the structure and data, but how do i "address" the fields and read them in again? has someone an example script that takes an nested array as input and returns a <form action="."> so that you can edit this array and use $_POST as new data? (hope someone can still follow me...)
Uhm........ If the array is always with the same structure, you can simply do: <form action="action.php" method="post"> Name: <input type="text" name="name"><br /> Address:<br /> - street: <input type="text" name="street"><br /> - zip: <input type="text" name="zip"><br /> ... </form> HTML: And then in your "action.php" script (the one that receives the POSTed data) just do: $this_guy['name'] = $_POST['name']; $this_guy['address']['street'] = $_POST['street']; ... PHP: I hope I understood your question, thou...
Something like the following might work, modify accordingly of course. Blargh, mis-read. Yes it's possible, if you still haven't solved it by the time you read this let me know and I'll help you out. <?php $this_guy = array( "name"=>"a guy", "address"=>array( "street" => "s. mile", "zip"=>"123", "city"=>"mooflake town"), "email"=>"spam@hotmail.com"); form($this_guy); function form($array) { foreach ($array as $k => $v) { if (is_array($v)) { foreach ($v as $key => $value) { echo "$key: <input type='text' name='$key' value='$value' /><br />"; } continue; } echo "$k: <input type='text' name='$k' value='$v' /><br />"; } } ?> PHP:
thanks, problem solved: function edit($array, $root) { $bf = "<ul>"."\n"; foreach($array as $key=>$value) { $key = $root.'::'.$key; if(is_array($value)) { $bf .= edit($value, $key); } else { $name = fieldname($key); $bf .= '<li><input name="'.$name.'" value="'.$value.'"></li>'."\n"; } } $bf .= '</ul>'."\n"; return $bf; } function fieldname($address) { //build correct form address $data = explode("::", $address); $formname = ""; foreach($data as $level=>$address) { if($level==0) { $formname = $address; } else { $formname .= '['.$address.']'; } } return $formname; } PHP: picouli: sorry, thats not really an option - my array has about ~90 fields or so, im not going to write a static form by hand for this.