簡體   English   中英

執行 json_encode 時 PHP 7.4 的日期時間問題(我使用的是 Carbon)

[英]Datetime issue with PHP 7.4 when doing json_encode (I am using Carbon)

我已將 PHP 從 7.0 升級到 7.4,當我將數據時間放入 json_encode 時,我的代碼的行為不同。 我在 PHP 錯誤中看到了這個問題,但我不知道如何修復它。 錯誤.php 錯誤 78383

現在,如果我使用日期時間執行 json_decode,我會得到一個日期的空數組 []。

對於此代碼:

$dataTest['text'] = "some text for the example";
$dataTest['date'] = Carbon::now();
$dateEncode = json_encode($dataTest);
$dateDecode = json_decode($dateEncode, TRUE);
dd($dataTest, $dateEncode, $dateDecode);

我得到:

array:2 [▼
  "text" => "some text for the example"
  "date" => Carbon {#905 ▼
    +"date": "2021-04-14 10:03:28.736535"
    +"timezone_type": 3
    +"timezone": "Europe/Madrid"
  }
]
"{"text":"some text for the example","date":[]}"
array:2 [▼
  "text" => "some text for the example"
  "date" => []
]

我可以強制 Carbon 在 json_encode 之前成為一個數組,但是要修復我的所有代碼需要做很多工作對於此代碼:

$dataTest['text'] = "some text for the example";
$dataTest['date'] = (array)Carbon::now();
$dateEncodeArray = json_encode($dataTest);
$dateDecodeArray = json_decode($dateEncodeArray, TRUE);
dd($dateEncodeArray, $dateDecodeArray );

我得到:

"{"text":"some text for the example","date":{"date":"2021-04-14 10:09:32.481792","timezone_type":3,"timezone":"Europe\/Madrid"}}"
array:2 [▼
  "text" => "some text for the example"
  "date" => array:3 [▼
    "date" => "2021-04-14 10:09:32.481792"
    "timezone_type" => 3
    "timezone" => "Europe/Madrid"
  ]
]

我正在使用 Carbon 1(nesbot/carbon 1.32.0 一個簡單的 API 擴展日期時間。)

有同樣問題的人嗎? 非常感謝,

只需將 Carbon 更新到更新的版本,就可以了:

$ composer require nesbot/carbon "^2.46"

現在您可以安全地執行以下操作:

$data = json_decode(json_encode(['date' => Carbon::now()]), true);

傾倒,這會給你:

array (

  'date' => '2021-04-14T12:53:04.403585Z',
)

如果您需要暫時使用 Carbon 1.x,您也可以嘗試屏蔽 Carbon:

use Carbon\Carbon as Charcoal; // Alias Carbon

class Carbon { // Mask original Carbon

    public static function __callStatic($method, $args) {

        // Whatever the given Carbon method returns, cast it to an array
        return (array) Charcoal::{$method}(...$args);  
    }

    // Add more methods as needed 
}

您可以為 Carbon 1 和 2 自定義 Carbon 實例的方式 output 在 JSON 與您想要的任何格式:

Carbon::serializeUsing(function ($date) {
    return $date->tz('UTC')->format('Y-m-d\TH:i:s.up');
});

echo json_encode(Carbon::now());

以上將為您提供與默認情況下 Carbon 2 相同的格式。

顯然,你應該升級,你落后了 54 個次要版本,你應該立即處理這個問題,它會為你節省很多更新的麻煩,而不是解決不兼容性以堅持不支持的版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM