简体   繁体   中英

PHP - Merge objects with existing objects in JSON file

I'm trying to append keys and values to an existing JSON object inside an array but can't figure out what I'm doing wrong. I've read several threads here but can't find anything related to my issue.

This is how the JSON-file should look like:

{  
"23-06-2017":{  
    "1:1":"text",
    "1:2":"text",
    "1:3":"text"
  },
"24-06-2017":{  
    "1:1":"text",
    "1:2":"text",
    "1:3":"text"
  }
}

So there's an array with date ( 23-06-2017 ) and there's keys and values inside it. "1:1": "text"

This is how my code looks like:

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

?>

And the $_POST['javascript_array_string'] looks like this 1:1,1:2,1:3

Any help appreciated!

Update: Added var_dump($tempArray) and also value of $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" } }

and value of $testDate is 24-06-2017

Update #2: So to clarify and help you understand what I'm trying to do..

I want these new (unique) keys and corresponding values: $foo

merged with the existing JSON-object: $tempArray

so that

{
 "24-06-2017":{
     "1:1":"text"
 }
}

becomes

{
"24-06-2017":{
    "1:1":"text",
    "1:2":"newValue",
    "1:3":"anotherValue"
  }
}

array_merge creates a new merged array. You must assign the result of array_merge if you want to modify one of the source arrays.

$tempArray[$testDate] = array_merge($tempArray[$testDate], $foo);

Example:

<?php

$testArray = [
  "24-06-2017" => [
    "1:1" => "text"
  ]
];


$foo = [
  "1:2" => "text",
  "1:3" => "text"
];


$testArray['24-06-2017'] = array_merge($testArray['24-06-2017'], $foo);

var_dump($testArray);

output:

array(1) {
  ["24-06-2017"]=>
  array(3) {
    ["1:1"]=>
    string(4) "text"
    ["1:2"]=>
    string(4) "text"
    ["1:3"]=>
    string(4) "text"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM