从数组中提取键值对并在php中对数组进行分组

In a single form, there are inputs named:

  • foo_name
  • foo_age
  • foo_bday
  • bar_cost
  • bar_date

After I submit the form using post as a method, I wanted to group the inputs into arrays like this:

$post = array(
    'foo' => array(),
    'bar' => array(),
    'baz' => array()
)

So all array_keys that starts with 'foo' will be pushed into 'foo' array and so as the others. Together ofcourse with their respective values.

Here is my try:

$post = array('foo' => array(), 'bar' => array(), 'baz' => array());
echo '<pre>';
foreach ($_POST as $key => $value) {
    if (startsWith($key, 'foo_')) {
        array_push($post['foo'], $key = $value);
    } else if(startsWith($key, 'bar_')) {
    } else if (startsWith($key, 'baz_')) {
    }
}

foreach ($post['foo'] as $key => $value) {
    echo $key . ' = ' . $value . '<br>';
}

The last foreach statement output this

0 = 1111
1 = 1112
2 = 210

instead of having its array_keys, the indeces where produced if $key where outputted

$post = array();

foreach($_POST as $key => $value) {
  $key = explode('_', $key);
  $post[$key[0]][$key[1]] = $value;
}

echo '<pre>';
print_r($post);
echo '</pre>';

Here is a phpFiddle

If you are able to name the input fields as you like, you can name them name="foo[name]" etc. from the beginning – this will give you arrays structured accordingly without the need to structure the data yourself using additional code.