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);
}
這個函數(shù)可以根據(jù)傳入的動態(tài)表單元素數(shù)組,遞歸地生成對應(yīng)的HTML表單元素。您可以根據(jù)需要添加更多類型的表單元素和相應(yīng)的處理邏輯。