dongpo4197 2018-03-06 12:27
浏览 37
已采纳

PHP多维数组到单个数组

I have a form that allows multiple values for inputs

Car One

<input type="text" name="vehicle[]" placeholder="Enter Your Vehicle" />

Car Two

<input type="text" name="vehicle[]" placeholder="Enter Your Vehicle" />

When submitted it translates to an array like so

["vehicle"]=>
  array(1) {
    [0]=>
    string(5) "Acura"
    [1]=>
    string(5) "Mazda"
 }

["doors"]=>
  array(1) {
    [0]=>
    string(6) "4 Door"
    [1]=>
    string(6) "2 Door"
  }

I want to then translate this to individual arrays that are like so

[VehicleOne]=>
  array(1) {
    [vehicle]=>
    string(5) "Acura"
    [doors]=>
    string(5) "4 door"
  }

I have a custom function I created that does this but I am wondering if there are native php methods that can be used instead of multiple loops?

So this is what I am currently using. Not every $_POST value is an array so I have to check and if is then I divide them up.

foreach ($fields as $key => $row) {

   if(is_array($row)){

     foreach ($row as $column => $value) {

        $doctors[$column][$key] = $value;

     }

  }

}

展开全部

  • 写回答

2条回答 默认 最新

  • donglianer5064 2018-03-06 12:36
    关注

    No need, just construct the array the way you want it in the inputs:

    <input type="text" name="data[0][vehicle]" placeholder="Enter Your Vehicle" />
    <input type="text" name="data[1][vehicle]" placeholder="Enter Your Vehicle" />
    <input type="text" name="data[0][doors]"   placeholder="Enter Your Doors" />
    <input type="text" name="data[1][doors]"   placeholder="Enter Your Doors" />
    

    Then $_POST will contain:

    Array
    (
        [data] => Array
            (
                [0] => Array
                    (
                        [vehicle] => Acura
                        [doors] => 4 door
                    )
    
                [1] => Array
                    (
                        [vehicle] => Maza
                        [doors] => 2 door
                    )
            )
    )
    

    If you can't/won't change the form, then something like:

    foreach($_POST['vehicle'] as $k => $v) {
        $result[] = ['vehicle' => $v, 'doors' => $_POST['doors'][$k]];
    }
    

    Will yield:

    Array
    (
        [0] => Array
            (
                [vehicle] => Acura
                [doors] => 4 door
            )
    
        [1] => Array
            (
                [vehicle] => Maza
                [doors] => 2 door
            )
    )
    

    Using something like VehicleOne etc. is pointless when using arrays as you are only doing this to make it unique, when 0, 1, etc. already is.

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部