問題:
給定兩個表示列名稱和標題列表的JSON 字串對於資料庫表,我們如何將它們合併以建立包含兩組資訊的單一JSON 字串?
第一個JSON 字串:
[ {"COLUMN_NAME": "ORDER_NO", "COLUMN_TITLE": "Order Number"}, {"COLUMN_NAME": "CUSTOMER_NO", "COLUMN_TITLE": "Customer Number"} ]
第二個JSON 字串:
[ {"COLUMN_NAME": "ORDER_NO", "DEFAULT_VALUE": "1521"}, {"COLUMN_NAME": "CUSTOMER_NO", "DEFAULT_VALUEE": "C1435"} ]
所需輸出:
[ {"COLUMN_NAME": "ORDER_NO", "COLUMN_TITLE": "Order Number", "DEFAULT_VALUE": "1521"}, {"COLUMN_NAME": "CUSTOMER_NO", "COLUMN_TITLE": "Customer Number", "DEFAULT_VALUEE": "C1435"} ]
解決方案:
至合併兩個JSON 字串,我們可以使用array_merge 和json_decode 函數。 json_decode 將 JSON 字串轉換為 PHP 陣列。 array_merge 合併這些數組,然後我們可以使用 json_encode 將合併後的陣列轉換回 JSON 字串。
$json1 = '[ {"COLUMN_NAME": "ORDER_NO", "COLUMN_TITLE": "Order Number"}, {"COLUMN_NAME": "CUSTOMER_NO", "COLUMN_TITLE": "Customer Number"} ]'; $json2 = '[ {"COLUMN_NAME": "ORDER_NO", "DEFAULT_VALUE": "1521"}, {"COLUMN_NAME": "CUSTOMER_NO", "DEFAULT_VALUEE": "C1435"} ]'; $array1 = json_decode($json1, true); $array2 = json_decode($json2, true); $mergedArray = array_merge($array1, $array2); $mergedJson = json_encode($mergedArray); echo $mergedJson;
輸出:
[ {"COLUMN_NAME": "ORDER_NO", "COLUMN_TITLE": "Order Number", "DEFAULT_VALUE": "1521"}, {"COLUMN_NAME": "CUSTOMER_NO", "COLUMN_TITLE": "Customer Number", "DEFAULT_VALUEE": "C1435"} ]
以上是如何在 PHP 中合併兩個 JSON 字串以建立單一組合 JSON 字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!