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!