0

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"}
]
2
  • 2
    $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 Commented Feb 10, 2019 at 20:27
  • 1
    @Cid what a rookie mistake, thanks for helping me out. Commented Feb 10, 2019 at 20:30

1 Answer 1

1

The trailing [] on the $cache variable's assignment are going to force the creation of a wrapper array. Once, removed, the code should work as expected, as in the following example:

<?php

$cache_data = '[{"item":"vla","amount":"3","shop":"Albert hijen"}]';
$cache = json_decode($cache_data, true);

$mapNewItem = array("item"=>"item02", "amount"=>"4", "shop"=>"Workshop 01");

array_push($cache, $mapNewItem);

echo json_encode($cache);
?>

Which outputs:

[{"item":"vla","amount":"3","shop":"Albert hijen"},{"item":"item02","amount":"4","shop":"Workshop 01"}]

You can test this live at https://ideone.com/MHmmTX

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.