dongyigua4468 2016-01-14 17:09
浏览 21
已采纳

如何用另一个数组推送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!

  • 写回答

1条回答 默认 最新

  • duanmian1085 2016-01-14 18:13
    关注

    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));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图