I'm trying to add an item to a JSON array using PHP but when I run the code(below) an new array object is added instead of an regular object. Can someone clear this up for me? I'm quite new to PHP and googling didn't solve the issue for me.
// Get data from cache
$cache_data = file_get_contents('shoppinglist.json');
$cache[] = json_decode($cache_data, true);
// Get data from url and parse it to an object
$data->item = $_GET['item'];
$data->amount = $_GET['amount'];
$data->shop = $_GET['shop'];
// Combine cache and data item
array_push($cache, $data);
// Write to shopping list file
$fp = fopen('shoppinglist.json', 'w');
fwrite($fp, json_encode($cache));
fclose($fp);
which results in:
[
[
[
{"item":"vla","amount":"3","shop":"Albert hijen"},
{"item":"vla","amount":"3","shop":"Albert hijen"}
],
{"item":"vla","amount":"3","shop":"Albert hijen"}
],
{"item":"vla","amount":"3","shop":"Albert hijen"}
]
$cache[] = json_decode($cache_data, true);remove that[]->$cache = json_decode($cache_data, true);so you don't put the decoded json in a subarray