2016-01-16 88 views
0

我通過HTML表單獲取用戶的詳細信息,並通過onclick表單提交,運行php文件save2json.php,它從HTML表單中檢索並將其張貼爲JSON在文件appointmentments.json中。如何合併PHP中數組下的兩個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)) 

我能得到什麼:[appointments.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" 
    } 
}] 

我想要什麼:[appointments.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" 
    } 

}] 

如果是在同一位醫生下,我想讓這兩個對象進入同一陣列。如果它不像醫生1和醫生2,在這種情況下,我希望它們與醫生3陣列分開。

感謝提前:)

+0

有沒有這樣的東西作爲JSON對象。 ':)' –

+0

您需要將佈局更改爲陣列格式以適用於所有醫生'id's,否則將會非常困難。你想改變它的方式? –

+0

糟糕。對不起。我沒有意識到這些條款,這很令人困惑。再次抱歉。 –

回答

1

這是把它放在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; 
?>