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

时间:2019-12-04 23:35:26

标签: php

我正在发布一个包含文本和文件的多部分,并尝试将数据传递给表单,但是这些数据是分开的,所以我想将它们组合起来。

$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()

{
    "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->文件-> all()

{
    "parkings": [{
        "generalInfo": "File.pdf",
        "places": [{
                "logo": "File1.png"
            },
            {
                "logo": "File2.png"
            }
        ]
    }]
}

然后我想将其合并为一个数组,得到这个:

{
    "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个数组的单个数组。不会将一个数组的数据添加到另一个数组的相应位置。

我想知道是否有某种方法可以自动而优雅地完成此任务。

1 个答案:

答案 0 :(得分:0)

希望这可以解决您的问题

$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"
}
]
}