add/combine json array to array in JSON file php

unsalted picture unsalted · Apr 25, 2013 · Viewed 7.5k times · Source

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.

Answer

Ali Akbar Azizi picture Ali Akbar Azizi · Apr 25, 2013

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.