Here is what i am doing, Storing values from a form to array and then storing that array into a file (array.jason).
if (isset($_POST['addEntity'])) {
$values = array_values($_POST);
print_r($values);
unset($values[1]);
var_dump($values);
$file_values = json_decode(file_get_contents('array.json'), true);
array_combine($file_values,$values);
file_put_contents("array.json",json_encode($values),FILE_APPEND);
}
Now, when i try to merge array from file ($file_values) to an array which i get from submit ($values) i am getting this error or warning :(
Warning: array_combine() expects parameter 1 to be array, null given in C:\Users\tej\PhpstormProjects\Final Year Project\index.php on line 9
So there are a few things wrong in your code which got you a few errors. First I will show you how you can fix your code and second what went wrong and what happened.
So to fix your code you have to assign the return value of array_combine()
back to $values
and just overwrite the file, since you added the new data to the old decoded one, e.g.
if (isset($_POST['addEntity'])) { $values = array_values($_POST); unset($values[1]); $file_values = json_decode(file_get_contents('array.json'), true); $values = array_combine($file_values,$values); file_put_contents("array.json", json_encode($values)); }
But what happened without that assignment and the appending of the file is. You just encoded your new data into JSON and appended it to your file. Means you created:
[DATA 1]
[DATA 2]
[DATA ...]
So when you tried to decode it again, all encoded data combined weren't valid anymore, even though they are as a single line they aren't as entire file. Which then lead json_decode()
return NULL
, since it wasn't valid JSON, and finally you tried to combine NULL with an array which got you a PHP error.