【问题标题】:Insert array into multidimensional array将数组插入多维数组
【发布时间】:2013-03-10 09:48:42
【问题描述】:

我有一个如下所示的数组:

{"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);
}

?>

我似乎无法将添加的数组合并到现有数组中的正确位置。

想法?

【问题讨论】:

    标签: php arrays multidimensional-array


    【解决方案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
    

    如果你愿意,你可以缩短它,但它尽可能接近你的代码;)

    【讨论】:

      【解决方案2】:

      我会使用 array_push 函数而不是 array_merge,因为在你的情况下,array_merge 改变了返回数组的结构,因为你将内部数组与新数组相结合。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 2012-10-18
        • 1970-01-01
        • 1970-01-01
        • 2013-10-06
        • 2011-12-12
        相关资源
        最近更新 更多