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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?