function createFormElement($element) {
if ($element['type'] == 'text') {
echo '<input type="text" name="' . $element['name'] . '" placeholder="' . $element['placeholder'] . '">';
} elseif ($element['type'] == 'textarea') {
echo '<textarea name="' . $element['name'] . '" placeholder="' . $element['placeholder'] . '"></textarea>';
} elseif ($element['type'] == 'select') {
echo '<select name="' . $element['name'] . '">';
foreach ($element['options'] as $option) {
echo '<option value="' . $option['value'] . '">' . $option['label'] . '</option>';
}
echo '</select>';
} elseif ($element['type'] == 'checkbox') {
echo '<input type="checkbox" name="' . $element['name'] . '" value="' . $element['value'] . '">';
}
// Recursively create sub-elements if any
if (isset($element['sub_elements'])) {
foreach ($element['sub_elements'] as $sub_element) {
createFormElement($sub_element);
}
}
}
使用示例:
$formElements = [
[
'type' => 'text',
'name' => 'username',
'placeholder' => 'Enter your username'
],
[
'type' => 'select',
'name' => 'gender',
'options' => [
['value' => 'male', 'label' => 'Male'],
['value' => 'female', 'label' => 'Female']
]
],
[
'type' => 'checkbox',
'name' => 'agree_terms',
'value' => 'yes'
]
];
foreach ($formElements as $element) {
createFormElement($element);
}
這個函數可以根據傳入的動態表單元素數組,遞歸地生成對應的HTML表單元素。您可以根據需要添加更多類型的表單元素和相應的處理邏輯。