我想用php准备json,如下所示。但是,服务部分不会嵌套。如何通过更正php代码获得如下所示的json输出?
foreach($this->input->post('name') as $key => $value){
$services = [];
foreach($this->input->post('services') as $value2){
$services[] = array(
'service_name' => $value2
);
}
$json[] = array(
'name' => $this->input->post('name')[$key],
'surname' => $this->input->post('surname')[$key],
'birthday' => $this->input->post('birthday')[$key],
'services' => $services
);
}
echo json_encode($json);
我想要这个:
[
{
"name":"aa",
"surname":"bb",
"birthday":"10.07.2019",
"services":[
{
"service_name":"test1",
"service_name":"test2",
},
]
},
{
"name":"cc",
"surname":"dd",
"birthday":"20.07.2019",
"services":[
{
"service_name":"test3",
"service_name":"test4",
},
]
}
]
答案 0 :(得分:0)
您可以尝试以下代码:
foreach($this->input->post('name') as $key => $value){
$services = [];
$count = 0;
foreach($this->input->post('services') as $value2){
$services["service".$count] = $value2;
$count++;
}
$json[] = array(
'name' => $this->input->post('name')[$key],
'surname' => $this->input->post('surname')[$key],
'birthday' => $this->input->post('birthday')[$key],
'services' => $services
);
}
$json = json_encode($json);
$json = preg_replace('/"service\d+"/', "service_name", $json);
echo $json;