猿问

在 PHP 中读取 JSON 以从日期字段创建字符串

我正在尝试从 PHP 中的 JSON 获取日期值:


{

  "data": [

    {

      "start": {

        "date": "2019-12-27 21:05:28.073000",

        "timezone_type": 3,

        "timezone": "UTC"

      },

      "final": {

        "date": "2019-12-28 20:59:43.153000",

        "timezone_type": 3,

        "timezone": "UTC"

      }

    }

  ]

}

我的 PHP 代码正在尝试读取 JSON,但我想我没有达到开始和最终的子级别。


我收到一个错误,没有返回任何内容。


我试图进入一个变量“2019-12-27 21:05:28 UTC+3”(开始)和另一个变量“2019-12-28 20:59:43 UTC+3”(最终)


<?php 

$json=file_get_contents("https://XXX/myjson.php");

$data =  json_decode($json);

if (count($data->data)) {

    // Open the table

    // Cycle through the array

    foreach ($data->data as $idx => $stand) {

        echo "first operation ".$stand->start."<br>";   

        echo "final operation ".$stand->final;   

    }}

?>


慕仙森
浏览 101回答 1
1回答

汪汪一只猫

问题在于您错误地给出了对象元素。看我的代码:$json='{&nbsp; "data": [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "start": {&nbsp; &nbsp; &nbsp; &nbsp; "date": "2019-12-27 21:05:28.073000",&nbsp; &nbsp; &nbsp; &nbsp; "timezone_type": 3,&nbsp; &nbsp; &nbsp; &nbsp; "timezone": "UTC"&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; "final": {&nbsp; &nbsp; &nbsp; &nbsp; "date": "2019-12-28 20:59:43.153000",&nbsp; &nbsp; &nbsp; &nbsp; "timezone_type": 3,&nbsp; &nbsp; &nbsp; &nbsp; "timezone": "UTC"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; ]}';$data =&nbsp; json_decode($json);if (count($data->data)) {// Open the table// Cycle through the arrayforeach ($data->data as $idx => $stand) {&nbsp; &nbsp; if(isset($stand->start)){&nbsp; &nbsp; &nbsp; &nbsp; echo "first operation ".$stand->start->date."<br>";&nbsp;&nbsp;&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; echo "final operation ".$stand->final->date;&nbsp; &nbsp;&nbsp; &nbsp; }}}
随时随地看视频慕课网APP
我要回答