如何在PHP中合并一个Array下的两个JSON

时间:2016-01-16 18:28:33

标签: php arrays json

我通过HTML表单获取用户的详细信息,并点击表单提交,我运行php文件save2json.php,它从HTML表单中检索,并在文件appointmentments.json中将其作为JSON发布。

save2json.php

$formdata = array(
  $_POST['doctor'] => array(
    'name'=> $_POST['name'],
    'phone'=> $_POST['phone'],       
    'bday'=> $_POST['bday'],
    'datepicker'=> $_POST['datepicker'],
  )
);    

$filetxt = 'appointments.json';    
$arr_data = array();       
if(file_exists($filetxt))
{          
  $jsondata = file_get_contents($filetxt); 
  $arr_data = json_decode($jsondata, true);
}           
$arr_data[] = $formdata;
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);    
if(file_put_contents('appointments.json', $jsondata)) 

我得到了什么: [appointmentments.json]

[{
    "Doctor #3": {
        "name": "0",
        "phone": "0",
        "bday": "0",
        "datepicker": "0"
    }
}, {
    "Doctor #3": {
        "name": "1",
        "phone": "1",
        "bday": "1",
        "datepicker": "1"
    }
}, {
    "Doctor #1": {
        "name": "2",
        "phone": "2",
        "bday": "2",
        "datepicker": "2"
    }
}, {
    "Doctor #2": {
        "name": "3",
        "phone": "3",
        "bday": "3",
        "datepicker": "3"
    }
}]

我想要的是什么: [appointmentments.json]

[{
    "Doctor #3": [{
            "name": "0",
            "phone": "0",
            "bday": "0",
            "datepicker": "0"
        },

        {
            "name": "1",
            "phone": "1",
            "bday": "1",
            "datepicker": "1"
        }
    ],
    "Doctor #1": {
        "name": "2",
        "phone": "2",
        "bday": "2",
        "datepicker": "2"
    },
    "Doctor #2": {
        "name": "3",
        "phone": "3",
        "bday": "3",
        "datepicker": "3"
    }

}]

如果是同一位医生,我想让两个对象都在同一个数组下。如果它不像Doctor 1和Doctor 2,在这种情况下,我希望它们与Doctor 3阵列分开。

提前致谢:)

1 个答案:

答案 0 :(得分:0)

这是第一次将其放入doctor数组键中的尝试:

<?php
    // build the array
    $docDetails = array(
        'name'=> $_POST['name'],
        'phone'=> $_POST['phone'],
        'bday'=> $_POST['bday'],
        'datepicker'=> $_POST['datepicker'],
    );

    // get the file's content as an array.
    $filetxt = 'appointments.json';
    if(file_exists($filetxt))
        $arr_data = json_decode(file_get_contents($filetxt), true);
    else
        $arr_data = array();
    $arr_data[$_POST['doctor']][] = $docDetails;
?>