Can I put associative arrays in form inputs to be processed in PHP?

后端 未结 3 991
栀梦
栀梦 2021-01-17 07:53

I know I can do things like , but is it possible to do things like and have it show up

相关标签:
3条回答
  • 2021-01-17 08:37

    Yes you can. you can even do name="foor[bar][]" and on for even more padding.

    0 讨论(0)
  • 2021-01-17 08:48

    You can do this in Drupal too, quite easily. The important thing you have to remember about is setting form '#tree' parameter to TRUE. To give you a quick example:

    function MYMODULE_form() {
      $form = array('#tree' => TRUE);
      $form['group_1']['field_1'] = array(
        '#type' => 'textfield',
        '#title' => 'Field 1',
      );
      $form['group_1']['field_2'] = array(
        '#type' => 'textfield',
        '#title' => 'Field 2',
      );
      $form['group_2']['field_3'] = array(
        '#type' => 'textfield',
        '#title' => 'Field 3',
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
      );
      return $form;
    }
    

    Now, if you print_r() $form_state['values'] in MYMODULE_form_submit($form, &$form_state), you will see something like this:

    Array
    (
        [group_1] => Array
            (
                [field_1] => abcd
                [field_2] => efgh
            )
    
        [group_2] => Array
            (
                [field_3] => ijkl
            )
    
        [op] => Submit
        [submit] => Submit
        [form_build_id] => form-7a870f2ffdd231d9f76f033f4863648d
        [form_id] => test_form
    )
    
    0 讨论(0)
  • 2021-01-17 08:50

    Let say we want to print student scores using the form below:

    <form action="" method="POST">
      <input name="student['john']">
      <input name="student['kofi']">
      <input name="student['kwame']">
      <input type="submit" name="submit">
    </form>
    

    and PHP code to print their scores:

    if(isset($_POST['submit']))
    {
        echo $_POST['student']['john'] . '<br />';
        echo $_POST['student']['kofi'] . '<br />';
        echo $_POST['student']['kwame'] . '<br />'; 
    }
    

    This will print the values you input into the field.

    0 讨论(0)
提交回复
热议问题