Reputation: 353
I have been trying to solve this problem for the better part of two days with no success. I am trying combine/add to a json array that is stored in a .json file on my server using php.
This is a short version of what I'm trying to combine.
box.json:
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"}]
posted json:
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]
This is what I need.
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]
This is what I get. (an array inside an array)
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]]
This is my code:
<?php
$sentArray = $_POST['json'];
$boxArray = file_get_contents('ajax/box.json');
$sentdata = json_decode($sentArray);
$getdata = json_decode($boxArray);
$sentdata[] = $getdata; /* I also tried array_push($sentdata, $getdata); */
$json = json_encode($sentdata);
$fsize = filesize('ajax/box.json');
if ($fsize <= 5000){
if (json_encode($json) != null) { /* sanity check */
$file = fopen('ajax/box.json' ,'w+');
fwrite($file, $json);
fclose($file);
}else{
/*rest of code*/
}
?>
Please help my sanity is starting to come in to question.
Upvotes: 1
Views: 7560
Reputation: 11
$box = json_decode(file_get_contents('ajax/box.json'));
$posted = json_decode($_POST['json']);
$merge = array_merge ((array)$box,(array)$posted);
Casting (array) prevent error if $box or $posted become null or false, it will be an empty array
Upvotes: 1
Reputation: 19539
Instead of this:
$sentdata[] = $getdata; /* I also tried array_push($sentdata, $getdata); */
Try:
$combinedData = array_merge($sentData, $getData);
$json = json_encode($combinedData);
By using array_merge you're combining the arrays into one instead of adding one array as a value into the other.
Note that I changed the name of your resulting data - try to avoid variables with the same name and different capitalization, it will make things much easier to understand (for you and for future developers supporting your code).
Cheers
Upvotes: 0
Reputation: 3496
here is your problem
$sentdata[] = $getdata;
use foreach
foreach($getdata as $value)
$sentdata[] = $value;
UPDATE:
but i think you need this for $sentdata
not $getdata
foreach($senttdata as $value)
$getdata[] = $value;
then put $getdata
to your file.
Upvotes: 1