Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Write To Javascript Object With PHP

Currently, my front end website uses a .js file that is hosted on dropbox as a "database". It is essentially a Javascript dictionary that is called, and then used. This is the format.

myDictionary = {
"Tag1":["Tag1","info1","info2"],
"Tag2":["Tag2","info1","info2"],
...
...

}
myDictionary2 = {
"Tag1":["Tag1","info1","info2"],
"Tag2":["Tag2","info1","info2"],
...
...

}

I'm starting to transition into PHP, and I wanted to know if it was possible to add new entries to this dictionary without messing things up. Basically, what I am asking is if there is a way of adding entires to a javascript dictionary, preferably without just adding the text, as it may get complicated. Thank You!

like image 580
Math and Science Avatar asked Dec 05 '25 21:12

Math and Science


1 Answers

Yes, it's possible using json_decode() and json_encode():

<?php

$myDictionary = json_decode('{
    "Tag1":["Tag1","info1","info2"],
    "Tag2":["Tag2","info1","info2"]
}');

$myDictionary->Tag3 = ["Tag3","info1","info2"];

echo json_encode($myDictionary, JSON_PRETTY_PRINT);

Output:

{
    "Tag1": [
        "Tag1",
        "info1",
        "info2"
    ],
    "Tag2": [
        "Tag2",
        "info1",
        "info2"
    ],
    "Tag3": [
        "Tag3",
        "info1",
        "info2"
    ]
}
like image 97
Mike Avatar answered Dec 08 '25 10:12

Mike