将数组插入多维数组 [英] Insert array into multidimensional array

查看:79
本文介绍了将数组插入多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数组:

I have an array that looks like this:

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

我想在日历中输入一个新数组,以实现此输出:

And I want to input a new array into this array but inside calendar to achieve this output:

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

这都是从表单发布中发生的。

This is all happening from a form post.

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

?>

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

I cant seem to merge the added array to the correct spot in the existing array.

想法?

推荐答案

尝试一下

$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

您可以根据需要缩短此时间,但这与您代码);)

you can shorten this up if you want, but this is as close to your code as possible ;)

这篇关于将数组插入多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆