Search code examples
phparrayspostfilteringfieldset

filtering post fields (using fieldsets?)


I'm having trouble filtering my post's values. When I post it will give back an array like:

Array ( [db-table] => afdeling 
        [box-2] => 2 
        [box-3] => 3 
        [db-fields] => array( random fields )
        [box-6] => 6
)

The form is build in 4 parts first some textboxes which are located inside a fieldset, then 4 checkboxes labeled 1 - 4 inside a 2nd fieldset, then some more textboxes inside a third fieldset and last, 4 more checkboxes labeled 5 - 8 inside a forth fieldset. the fieldsets are named:

  • db-tabledata
  • checkboxes-1
  • db-fielddata
  • chechboxes-2

I've also looked for things like "filtering similar named fields from a post" and tried it with some array functions like array_keys/filter with 2 for loops to get them piece by piece but I didn't get that to work.

In the end what I expect to do is filter the array in the $_POST to a structure like this:

Array ( 
  'db-data' =>    array( [db-table] => afdeling 
                         [db-fields] => array( random fields )
                  ),
  'checkboxes' => array( [box-2] => 2 
                         [box-3] => 3 
                         [box-6] => 6
                  )           
)

So can someone push me in the right direction on filtering the fields out of the array?

ADDITION:

At this moment I'm trying to order the array alphabetical so that the box-? fields will be in the beginning or the end of the array.

problem with this however is that the box-? fields can occur 1 to 8 times. So I need some kind of way to count every array key that looks like: box-?. To know how many of those there are.


Solution

  • You can name your fields using [], for example:

    <input name="db-data[db-table]" ... />
    <input name="db-data[db-fields][first-field]" ... />
    <input name="db-data[db-fields][second-field]" ... />
    
    <input name="checkboxes[box-1]" ... />
    <input name="checkboxes[box-2]" ... />
    

    In this case your $_POST array will already have the structure that you want.