0

I have a JSON file with an array called "foods". Inside this array I want to push a new object with name, type and price.

{
    "foods":[
        {
            "name": "Name1",
            "tyoe": "Type1",
            "price": "Price1"
        },
        {
            "name": "Name2",
            "type": "Type2",
            "price": "Price2"
        }
    ]
}

The logic is:
I receive from $_POST a name, type and price. (I'ts a simple form -- it's working ok)
So I want to push these data with PHP inside the "foods" array in JSON file. The result would be like this:

{
    "foods":[
        {
            "name": "Name1",
            "tyoe": "Type1",
            "price": "Price1"
        },
        {
            "name": "Name2",
            "type": "Type2",
            "price": "Price2"
        },
        {
            "name": "NAME3",
            "type": "TYPE3",
            "price": "PRICE3"
        }
    ]
}

Wrong example that I'm trying to fix it:

$name = $_POST['name'];
$type = $_POST['type'];
$price = $_POST['price'];

//Do I need to create this array to push inside JSON array "foods"?
$arrayFoods = array(        
    'name' => $name,
    'type' => $type,
    'price' => $price
);

$my_file = file_get_contents('database/file.json');

//Do I need to decode the JSON file to access the array "foods" to push my $arrayFoods? 
//How do I access the "foods" array in JSON file and push my $arrayFoods?
$fileDecode = json_decode($my_file);

Thanks!

3
  • $fileDecode = json_decode($my_file, true); $fileDecode[] = $arrayFoods; Commented Jan 14, 2016 at 17:21
  • but how do I access the array called "foods" inside JSON File? Commented Jan 14, 2016 at 17:26
  • Only read, modify and write back Commented Jan 14, 2016 at 17:28

1 Answer 1

1

Following what you have done

$food = new stdClass;
$food->name = $name;
$food->type = $type;
$food->price = $type;
$my_file = file_get_contents('database/file.json');
$fileDecode = json_decode($my_file);
array_push($fileDecode->foods, $food);
//to save
file_put_contents('database/file.json', json_encode($fileDecode));
Sign up to request clarification or add additional context in comments.

9 Comments

can't push an array onto an object.
what are you talking about?
so you spam a bunch of crap, make a semi work around my answer, post your answer and downvote me? WTF are you kid?
please post your decoded json file with var_dump($fileDecode)
Oh yea! It worked! But when I push, the data don't save in the file?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.