简体   繁体   中英

Extracting a key value pairs from an array and group the array in 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

如果您能够根据需要命名输入字段,则可以从头开始将它们name="foo[name]"等 - 这将为您提供相应的数组结构,而无需使用其他代码自行构建数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM