dongyun51582 2017-02-20 05:40
浏览 6
已采纳

在下拉列表中发布多维数组

I have two dropdown option with same name like following.

<form action="" method="post">
    <select name="freeoptions[]">
        <option value="[7][4]">Black</option>
        <option value="[7][5]">Blue</option>
        <option value="[7][3]">Red</option>
    </select>


    <select name="freeoptions[]">
        <option value="[9][11]">Small</option>
        <option value="[9][15]">Large</option>
        <option value="[9][13]">XL</option>
    </select>

    <input type="submit" name="submit" value="submit">
</form>

Now when i am posting form, getting post data in array like,

Array
(
    [freeoptions] => Array
        (
            [0] => [7][4]
            [1] => [9][11]
        )
)

But I want this array something like

Array
        (
            [freeoptions] => Array
            (
                [0] => Array
                (
                        [id] => [7]
                        [value] => [4]
                )
                [1] => Array
                (
                        [id] => [9]
                        [value] => [11]
                )
            )
        )

Can anyone please help me how to do this. Thanks,

  • 写回答

2条回答 默认 最新

  • doolo00026 2017-02-20 06:08
    关注

    Anything in a "value" attribute is sent as a literal string, regardless of it's content, so you can't post a value as an array out of the box.

    You can always have both values in the same value attribute and split it in the back end.

    Example in HTML:

    <option value="7;4"></option>
    

    Then do something like this in your back end:

    $data = [];
    
    // Loop all freeoptions params
    foreach ($_POST['freeoptions'] as $opt) {
        // Split the value on or separator: ;
        $items = explode(';', $opt);
    
        if (count($items) != 2) {
            // We didn't get two values, let's ignore it and jump to the next iteration
            continue;
        }
    
        // Create our new structure
        $data[] = [
            'id'    => $items[0], // Before the ;
            'value' => $items[1], // After the ;
        ];
    }
    

    The $data-array should now contain the data structure you want.

    If you want to keep using the $_POST-variable instead, just overwrite the original data after the foreach:

    $_POST['freeoptions'] = $data;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?