du6jws6975 2017-11-10 05:47
浏览 106
已采纳

如何在php中构造数据以获得正确的json结果?

I am working in php and need to export a json document in the following format (below).

I know how to do the actual export with file_put_contents($data_file, json_encode($json_array)); but I'm struggling with what format I need to have the $json_array in to achieve the desired results.

I need the final json file to be formatted like this:

{
  "2016": [
      {
        "date": "2016/01/01",
        "close": 837
      },
      {
        "date": "2016/12/01",
        "close": 769
      }
    ],
  "2015": [
      {
        "date": "2015/01/01",
        "close": 637
      },
      {
        "date": "2015/12/01",
        "close": 669
      }
    ],
  "2014": [
      {
        "date": "2014/01/01",
        "close": 537
      },
      {
        "date": "2014/12/01",
        "close": 569
      }
    ]
}

Is this accomplished by exporting an array with 3 keys, each containing a multidimensional array? Or an array of objects of some type?

Maybe I'm overthinking this, but I've been working this problem all day and have not been able to get the desired results.

To me the structure looks like an array; with the (first) key of 2016 and a value of an array, but then what's inside that array?

  • 写回答

1条回答 默认 最新

  • dqqxkq4047 2017-11-10 05:56
    关注

    It's pretty straight forward. Just create an array in PHP with the same leves and keys:

    $data = [
        '2016' => [
            [
                "date"  => "2016/01/01",
                "close" =>  837
            ],
            [
                "date"  => "2016/12/01",
                "close" => 769
            ],
        ],    
        '2015' => [
            [
                "date"  => "2015/01/01",
                "close" => 637
            ],
            [
                "date"  => "2015/12/01",
                "close" => 669
            ],
        ],    
        // ... and so on
    ];
    

    Demo: https://3v4l.org/cfHqs

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了