处理表单后置值和数组操作

时间:2014-07-31 09:44:31

标签: php html arrays forms arraylist

我有$_POST这样的值。

以下值来自表格。

我想做的是。

  1. 作者代码1和作者代码3有一个名为[chkName_1] => 1的新标志 因此,仅此值应插入数据库

  2. 作者代码2没有标志,应该被忽略。

    [author_code_1] => 1
    [author_name_1] => Author 1
    [chkName_1] => 1
    [author_code_2] => 2
    [author_name_2] => Author 2
    [author_code_3] => 3
    [author_name_3] => Author 3
    [chkName_3] => 1
    
  3. 上面的数组应该在循环中运行,而insert语句看起来应该是这样的。

    insert Into author_log (`author_code`,`author_name`) values (1,'Author 1');     
    insert Into author_log (`author_code`,`author_name`) values (3,'Author 3');     
    

    换句话说,检查标志值,如果设置为1,则插入db。

    谢谢,
    Kimz
    PS:我甚至不知道如何处理这个并运行forloop。

1 个答案:

答案 0 :(得分:1)

<?php
    $authors = array(
        'author_code_1' => 1,
        'author_name_1' => 'author1',
        'chkName_1' => 1,
        'author_code_2' => 2,
        'author_name_2' => 'author2',
        'author_code_3' => 3,
        'author_name_3' => 'author3',
        'chkName_3' => 1
    );

    // _ CODE STARTS HERE
    $list = array();
    foreach ($authors as $key => $entry) {
        if (strpos($key, 'author_name_') !== false) {
            $index = str_replace('author_name_', '', $key);
            $list[$index]['name'] = $entry;
        } elseif (strpos($key, 'author_code_') !== false) {
            $index = str_replace('author_code_', '', $key);
            $list[$index]['code'] = $entry;
        } else if (strpos($key, 'chkName_') !== false) {
            $index = str_replace('chkName_', '', $key);
            $list[$index]['chk'] = $entry;
        }

    }
    // ^ CODE ENDS HERE

    print_r($list);
?>

使用此代码将事务请求的混乱转换为更易于操作的内容。 虽然你应该真的修改你的表格。

Test