Reputation: 33
So currently I'm working on a project that requires the use of PHP and JSON. The way I have currently set up my code is so that I read the JSON file in using file_get_contents and then use the built in json_decode() function. Everything is reading perfectly, it's the writing part that is giving me trouble.
The way I have my JSON tree set up is:
{
"test":[
{
"testName":"Winter 2011",
"testDate":"12/04/2011",
"testTime":"2:00pm",
"testRoom":"room",
"cap": 10,
"spotsLeft": 0,
"student":[
{
"fname":"Bob",
"lname":"Roberts",
"usrnm":"bobr",
"email":"[email protected]"
}
]
}
]
}
To get the right test (since there will be multiple tests) I'm using a foreach loop
and then I make sure there isn't a duplicate. At this point I'm ready to add a new student to the JSON file so I call:
`
$file = file_get_contents('testDates.json');
$json = json_decode($file, true);
//Go through each test in the file
foreach ($json[test] as $t){
.....
//Works if I only do $t[student] but that only adds it to the $t[] and not the
//JSON file. Can't seem to get it to add to the whole JSON string.
array_push($json[$t][student], $newStudent);
echo json_encode($json);
.....
//Use a file_put_contents later to write the file out
Any thoughts would be extremely helpful. It's probably a pointer error to a certain point int he array but a second set of eyes never hurt. Thanks.
Upvotes: 1
Views: 2281
Reputation: 21367
Try this:
$json = json_decode($jsonString);
if($json["color"] == "blue"){
...
}
$json["language"] = "php";
$newJsonString = json_encode($json);
Isn't that easy?
Upvotes: 0
Reputation: 6030
You're using wrong $json[$t] inside foreach instead of $json["test"][$t] and also you need to use key-value pairs
$testVal = $json["test"];
foreach ($testVal as $key => $val){
. . .
array_push($testVal[$key]["student"], $newStudent);
. . .
}
P.S. use $json['test'] instead of $json[test], the first one causes syntax warning which PHP interprets as string "test" (in your case it's working:) )
Upvotes: 0
Reputation: 17010
$t
is a copy, it is not referencing original object. This appens with every foreach cycle. Use instead:
foreach ($json[test] as $k => $t){
array_push($json[test][$k][student], $newStudent);
...
}
Or you can try:
foreach ($json[test] as &$t){
array_push($t[student], $newStudent);
...
}
See here to learn how foreach works: http://php.net/manual/en/control-structures.foreach.php
Upvotes: 3