簡體   English   中英

將 Json 字符串轉換為 Json 對象 PHP

[英]Converting Json String to Json Object PHP

我有一個 json 輸出作為這個

"data": [
    {
        "id": 1,
        "schedule": "{\"batch\": 1, \"times\": \"18:25:00.000000\"},{\"batch\": 1, \"times\": \"18:25:00.000000\"}"
    }

我想這樣顯示

"data": [
    {
        "id": 1,
        "schedule": [{"batch": 1, "times": "18:25:00.000000"},
                     {"batch": 1, "times": "18:25:00.000000"}]
    }

我已經嘗試了我能想到的一切,希望得到一些幫助

您的輸入 JSON 和預期的輸出 JSON 都不是格式正確的。 json_decode()在兩者上都返回NULL

在不確定您的輸入是什么樣的(或您想要的輸出是什么)的情況下,這里有一個我懷疑是您所追求的東西的演示。 請參閱注釋以獲取解釋。

<?php

// Your input JSON, corrected to well-formed syntax.
$string = '{"data": [
    {
        "id": 1,
        "schedule": "{\"batch\": 1, \"times\": \"18:25:00.000000\"},{\"batch\": 1, \"times\": \"18:25:00.000000\"}"
    }]}';

// Convert into native array.
$array = json_decode($string, TRUE);
// Make 'schedule' an array of the two batches.
$array['data'][0]['schedule'] = json_decode("[{$array['data'][0]['schedule']}]", TRUE);

echo json_encode($array) . "\n";
// {"data":[{"id":1,"schedule":[{"batch":1,"times":"18:25:00.000000"},{"batch":1,"times":"18:25:00.000000"}]}]}

暫無
暫無

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

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