dqoqnmb163241 2013-04-03 04:42
浏览 146
已采纳

从数组中提取键值对并在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

展开全部

  • 写回答

2条回答 默认 最新

  • duandu8202 2013-04-03 04:50
    关注
    $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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?