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表单元素。您可以根据需要添加更多类型的表单元素和相应的处理逻辑。