Insert a key:value pair into an array based on another key:value pair
Insert a key:value pair into an array based on another key:value pair
(OP)
I am trying to insert a key:value pair into an array based on another key:value pair. The json array is in a text file. I am not getting any errors, but nothing is inserted. After insertion it should look like the first array. The key and new value comes from a form.
Here is the array meetinfo_arrayTest.txt
Here is my code.
Any help would be appreciated.
Here is the array meetinfo_arrayTest.txt
CODE -->
[{"meetdate":"2019-03-23","topic":"Hypertension", "handout":"htn"}, {"meetdate":"2019-04-18","topic":"TBA"}, {"meetdate":"2019-05-02","topic":"TBA"}]
Here is my code.
CODE --> php
//retrieve values from form $meetdate = $form->getValue('meetdate'); $acronym = $form->getValue('ho_acronym'); //Retrieve the data from our text file. $fileContents = file_get_contents('../editor/textfiles/meetinfo_arrayTest.txt'); //Convert the JSON string back into an array. $infodecoded = json_decode($fileContents, true); foreach($fileContents as $row) { if (($row['meetdate']) == $meetdate) { $row['handout'] = $acronym; }} //Save the JSON string to a text file. $infoencoded = json_encode($infodecoded); file_put_contents("../editor/textfiles/meetinfo_arrayTest.txt", $infoencoded);
RE: Insert a key:value pair into an array based on another key:value pair
$row holds a copy of current array item. Modifying it does not affect $fileContents. So better explicitly change the array :
CODE --> PHP ( fragment )
Alternatively you can change $row into reference, but that is not recommended practice as later reuse of $row after the loop will still alter the last referred item :
CODE --> PHP ( fragment )
Feherke.
feherke.github.io
RE: Insert a key:value pair into an array based on another key:value pair