2013-03-21 129 views
1

我有一個數組,看起來像這樣:插入數組多維數組

{"calendar":{"date":"1","event":"1","description":"","code":"lab"}} 

我想輸入一個新的數組到這個陣列,但裏面日曆來實現這樣的輸出:

{"calendar": 
    {"date":"1","event":"1","description":"","code":"lab"} 
    {"date":"2","event":"2","description":"","code":"lab"} 
} 

這一切都發生在一個表單發佈。

<?php 
$dy_date = $_GET['dy_date']; 
$dy_event = $_GET['dy_event']; 
$dy_description = $_GET['dy_description']; 
$dy_code = $_GET['dy_code']; 

$calendar = array("calendar" => array("date" => $dy_date, "event" => $dy_event, "description" => $dy_description, "code"=> $dy_code)); 


$calendar_check = json_decode(file_get_contents('../calendar_dynamic.js'),true); 

$updated_cal = array(); 
foreach($calendar_check as $data){ 
    $updated_cal["date"] = $dy_date; 
    $updated_cal["event"] = $dy_event; 
    $updated_cal["description"] = $dy_description; 
    $updated_cal["code"] = $dy_code; 
    $updated_cal = array_merge($calendar_check['calendar'], $updated_cal); 
    $filename = "../calendar_dynamic.js"; 
    file_put_contents($filename, json_encode($updated_cal), FILE_APPEND); 
} 

?> 

我似乎不能將添加的數組合併到現有數組中的正確位置。

想法?

回答

1

試試這個

$filename = "../uc3_stats/calendar_dynamic.js"; 

$dy_date = $_GET['dy_date']; 
$dy_event = $_GET['dy_event']; 
$dy_description = $_GET['dy_description']; 
$dy_code = $_GET['dy_code']; 

$newentry_calendar = array("calendar" => array("date" => $dy_date, "event" => $dy_event, "description" => $dy_description, "code"=> $dy_code)); 

$old_calendar = json_decode(file_get_contents($filename),true); 

$new_calendar = $old_calendar; //keep old entries 
$new_calendar['calendar'][] = $newentry_calendar['calendar']; //add new entry 
file_put_contents($filename, json_encode($new_calendar)); // save to file 

,你可以,如果你想縮短這個,但是這是接近你的代碼成爲可能;)

+0

謝謝像魅力一樣工作。 – JMP 2013-03-21 18:58:48

+0

不客氣。 – itsid 2013-03-23 00:38:21

1

我會用array_push函數代替array_merge,因爲在你的case array_merge將返回數組的結構更改爲將內部數組與新數組組合在一起。

array_push ($calendar_check['calendar'], $updated_cal)