首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >组合$request->request和$request->files数组

组合$request->request和$request->files数组
EN

Stack Overflow用户
提问于 2019-12-05 07:35:27
回答 1查看 71关注 0票数 0

我正在张贴文本和文件的多部分,并试图传递数据到表单,但这些数据是分开的,所以我想把它们组合起来。

代码语言:javascript
复制
$request->request->all()
$request->files->all()

$form = $this->createForm(ParkingType::class, new Parking());
$form->submit($INeedToPassTheCombinedArray);
if ($form->isValid()) {
    return $form->getData();
}

这两个数组具有相同的结构。

例如:

$request->request->all()

代码语言:javascript
复制
{
    "name": "Test",
    "taxId": "asd12",
    "nationality": "england",
    "parkings": [{
        "total": 4,
        "capacity": 928,
        "places": [{
                "total": 123,
                "name": "test",
                "address": "test"
            },
            {
                "total": 123,
                "name": "test",
                "address": "test"
            }
        ]
    }]
}

$request->files->all()

代码语言:javascript
复制
{
    "parkings": [{
        "generalInfo": "File.pdf",
        "places": [{
                "logo": "File1.png"
            },
            {
                "logo": "File2.png"
            }
        ]
    }]
}

我想把它们合并到一个单独的数组中,得到这个:

代码语言:javascript
复制
{
    "name": "Test",
    "taxId": "asd12",
    "nationality": "england",
    "parkings": [{
        "total": 4,
        "capacity": 928,
        "generalInfo": "File.pdf",
        "places": [{
                "total": 123,
                "name": "test",
                "address": "test",
                "logo": "File1.png"
            },
            {
                "total": 123,
                "name": "test",
                "address": "test",
                "logo": "File2.png"
            }
        ]
    }]
}

我尝试使用array_merge,但结果是一个包含2个数组的数组。它不是将一个数组的数据添加到另一个数组的相应位置。

我想知道是否有一些方法可以自动而优雅地做到这一点。

EN

回答 1

Stack Overflow用户

发布于 2019-12-05 18:20:44

希望这能解决你的问题

代码语言:javascript
复制
$data1 = json_decode($data,true);// first post array
$data2 = json_decode($file,true);//second file array
foreach($data1['parkings'] as $key=>&$val){ // Loop though one array
   $val2 = $data2['parkings'][$key]; // Get the values from the other array
   $val += $val2; // combine 'em
   foreach($val['places'] as $k=>&$v){
       $val3 = $val2['places'][$k]; // Get the values from the other array
       $v  += $val3; // combine 'em
   }
 }
echo json_encode($data1);
{
 "name": "Test",
 "taxId": "asd12",
 "nationality": "england",
 "parkings": [
  {
  "total": 4,
  "capacity": 928,
  "places": [
    {
      "total": 123,
      "name": "test",
      "address": "test",
      "logo": "File1.png"
    },
    {
      "total": 123,
      "name": "test",
      "address": "test",
      "logo": "File2.png"
    }
  ],
  "generalInfo": "File.pdf"
}
]
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59186128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档