简体   繁体   中英

PHP create json with foreach loop

I want to prepare json with php as follows. But, the services section does not occur nested. How can I get json output as below by correcting php code?

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);

I want this:

[
   {
      "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",
          },
       ]
   }
]

You can try following code:

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM