【发布时间】:2017-06-24 02:11:18
【问题描述】:
我正在尝试将键和值附加到数组内的现有 JSON 对象,但无法弄清楚我做错了什么。我在这里阅读了几个主题,但找不到与我的问题相关的任何内容。
这是 JSON 文件的样子:
{
"23-06-2017":{
"1:1":"text",
"1:2":"text",
"1:3":"text"
},
"24-06-2017":{
"1:1":"text",
"1:2":"text",
"1:3":"text"
}
}
所以有一个带日期的数组 (23-06-2017),里面有键和值。 "1:1": "text"
这就是我的代码的样子:
<?php
$testArray = explode(',' $_POST['javascript_array_string']);
$testText = $_POST['testText'];
$testDate = $_POST['testDate'];
$foo = array();
foreach($testArray as $value){
$foo[$value] = "text";
}
$oldJSON = file_get_contents("json/test.json");
$tempArray = json_decode($oldJSON, true);
//array_push($tempArray, $foo); // Tried this and it adds a new array
//$tempArray[$testDate] = $foo; //This just replaces the old keys with new ones.
array_merge($tempArray[$testDate], $foo); //And with this one, nothing happens.
$jsonData = json_encode($tempArray);
file_put_contents("json/test.json");
?>
$_POST['javascript_array_string'] 看起来像这样1:1,1:2,1:3
任何帮助表示赞赏!
更新:添加了var_dump($tempArray)以及$testDate的值
array(2) { ["23-06-2017"]=> array(3) { ["2:17"]=> string(4) "ille" ["2:18"]=> string(4) "ille" ["2:19"]=> string(4) "ille" } ["24-06-2017"]=> array(1) { ["1:17"]=> string(4) "ille" } }
$testDate 的值为24-06-2017
更新 #2: 澄清并帮助您了解我正在尝试做的事情..
我想要这些新的(唯一的)键和对应的值:$foo
与现有 JSON 对象合并:$tempArray
这样
{
"24-06-2017":{
"1:1":"text"
}
}
变成
{
"24-06-2017":{
"1:1":"text",
"1:2":"newValue",
"1:3":"anotherValue"
}
}
【问题讨论】:
-
is $tempArray[$testDate] 是一个数组吗?
-
是的,$tempArray[$testDate] 是一个数组。整个 $tempArray 包含我想要附加值的当前 JSON 文件。
-
可以 var_dump 并发布
$tempArray[$testDate]吗? -
更新了
$tempArray的 var_dump 以及$testDate的值,尽管这是所有内容的真实值。 -
那你为什么要使用 array_merge 呢? if $tempArray[$testDate] = '24-06-2017' 它怎么是一个数组?