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?

图片转代码服务由CSDN问答提供 功能建议

我在php工作,需要以下列格式导出json文档(如下所示)。

我知道如何使用 file_put_contents($ data_file,json_encode($ json_array)); 进行实际导出,但我正在努力处理我需要的格式 使用$ json_array来实现所需的结果。

我需要将最终的json文件格式化为:

  {\  n“2016”:[
 {
“date”:“2016/01/01”,
“close”:837 
},
 {
“date”:“2016/12/01”  ,
“关闭”:769 
} 
],
“2015”:[
 {
“日期”:“2015/01/01”,
“关闭”:637 
},  
 {
“date”:“2015/12/01”,
“close”:669 
} 
],
“2014”:[
 {
“date”:“2014 /  01/01“,
”关闭“:537 
},
 {
”日期“:”2014/12/01“,
”关闭“:569 
} 
] 
} \  n   
 
 

这是通过导出一个包含3个键的数组来完成的,每个键都包含一个多维数组吗? 或者是某种类型的对象数组?

也许我正在过度思考这个问题,但我整天都在解决这个问题并且无法获得理想的结果。

对我而言,结构看起来像一个数组; 使用2016的(第一个)键和数组的值,但那个数组里面有什么?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题