簡體   English   中英

如何在PHP中將多個對象轉換為1個JSON字符串

[英]How to convert multiple objects into 1 JSON string in PHP

我的應用程序有一個報告列表,每個“報告”在PHP中都定義為一個新對象。 我正在嘗試制作一個基本的API,我想在1個JSON字符串中顯示所有“報告”的列表。 我的以下代碼很好地將1個對象編碼為JSON,但是如何獲取所有對象並將它們全部轉換為1個長JSON字符串?

我知道我可以創建一個對象數組,但是它返回這些括號[],並且我不希望JSON字符串中包含這些括號。

class report {
    public $report_name;
    public $report_value;
    public $report_benchmark;
    public $report_result;

    public function __construct($report_name, $report_value, $report_benchmark, $report_result) {
        $this->report_name = $report_name;
        $this->report_value = $report_value;
        $this->report_benchmark = $report_benchmark;
        $this->report_result = $report_result;
    }
}

$item = new report('test', 0, 0, 'OK');
echo json_encode($item, JSON_PRETTY_PRINT);

正如@JimL所建議的那樣,您可以簡單地在數組中添加一些對象,然后將其編碼為json。

$item = array();
$item[] = new report('test', 0, 0, 'OK');
$item[] = new report('test2', 0, 0, 'OK');
echo json_encode($item, JSON_PRETTY_PRINT);

產生:

[{
    "report_name": "test",
    "report_value": 0,
    "report_benchmark": 0,
    "report_result": "OK"
}, {
    "report_name": "test",
    "report_value": 0,
    "report_benchmark": 0,
    "report_result": "OK"
}]

請注意,您可以在此處驗證產生的json

您可以做這樣的事情。

$item = array();
$item['report1'] = $item = new report('test', 0, 0, 'OK');
$item['report2'] = $item = new report2('test', 0, 0, 'OK');
$item['report3'] = $item = new report3('test', 0, 0, 'OK');
echo json_encode($item, JSON_PRETTY_PRINT);

創建一個關聯數組並為所有對象分配一個意義完整的鍵,這將有助於輕松訪問每個特定的報告。

暫無
暫無

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

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