Search code examples
phparraysjsonappendmerging-data

Append rows of a 2d array to another 2d arrays with array_push()


I am trying to create a JSON array using php. Every time I post a new array the new one needs to append in front of the old array.

I have my code working however, it creates a strange format like [{},[{},[{}]]].

The format I need for my JSON array to be is [{},{},{}...]

[{"Reg_Date":"28-07-2999","Name":"aaa","Surname":"aaa","VideoPath":"aaa","MyComment":"aaa", "ThumbPath":"aaa", "UserId":"aaa"},
{"Reg_Date":"18-07-2015","Name":"bbb","Surname":"bbb","bbb":"bbb","MyComment":"bbb", "ThumbPath":"bbb", "UserId":"bbb"}]

How can I create my array properly?

php:

$results = array(
    array(
        "Reg_Date" => $Reg_Date, 
        "Name" => $NameUser, 
        "Surname" => $SurnameUser, 
        "VideoPath" => $VideoPath, 
        "MyComment" => $MyComment, 
        "ThumbPath" => $ThumbPath, 
        "UserId" => $UserId
    )
);

$inp = file_get_contents('video_JSON_Test.json');
$arr = json_decode($inp);

array_push($results, $arr);

$fp_login = fopen('video_JSON_Test.json', w);
fwrite($fp_login, json_encode($results));
fclose($fp_login);

print_r($results);
echo $NameUser . $SurnameUser, $MyComment . "\n";
echo json_encode($arr);

Solution

  • Replace:

    $arr = json_decode($inp);
    array_push($results, $arr);
    

    with:

    $arr = json_decode($inp, true);
    $results = array_merge($results, $arr);