如何用另一个数组推送JSON文件中的PHP数组

如何用另一个数组推送JSON文件中的PHP数组

问题描述:

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!

我有一个带有名为“foods”的数组的JSON文件。 在这个数组中,我想推送一个名称,类型和价格的新对象。 p>

  {
“食物”:[
 {
“name”:“Name1  “,
”tyoe“:”Type1“,
”price“:”Price1“
},
 {
”name“:”Name2“,
”type“:”Type2“,
  “price”:“Price2”
} 
] 
} 
  code>  pre> 
 
 

逻辑是:
我从$ _POST收到一个名字,类型 和价格。 (我是一个简单的表单 - 它工作正常)
我想用PHP将这些数据推送到JSON文件中的“foods”数组中。 结果如下: p> { “食物”:[ { “name”:“Name1”, “tyoe”:“Type1”, “price”:“Price1” }, { “name”:“Name2”, “type”:“Type2”, “price”:“Price2” }, { “name”:“NAME3” , “类型”:“TYPE3”, “价格”:“PRICE3” } ] } code> pre>

我的错误示​​例 试图修复它: p>

  $ name = $ _POST ['name']; 
 $ type = $ _POST ['type']; 
 $ price =  $ _POST ['price']; 
 
 //我是否需要创建此数组来推送JSON数组“食物”?
 $ arrayFoods = array(
'name'=> $ name,
  'type'=> $ type,
'price'=> $ price 
); 
 
 $ my_file = file_get_contents('database / file.json'); 
 
 //我需要吗? 解码JSON文件以访问数组“食物”t  o推我的$ arrayFoods?  
 //如何访问JSON文件中的“foods”数组并推送我的$ arrayFoods?
 $ fileDecode = json_decode($ my_file); 
  code>  pre> 
 
 

谢谢! p> div>

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));