php 數(shù)組可通過 json_encode() 函數(shù)轉(zhuǎn)換為 json 字符串(例如:$json = json_encode($array);),反之亦可用 json_decode() 函數(shù)從 json 轉(zhuǎn)換為數(shù)組($array = json_decode($json);)。其他技巧還包括:避免深度轉(zhuǎn)換、指定自定義選項以及使用第三方庫。
PHP 數(shù)組轉(zhuǎn) JSON - 快捷技巧
介紹
在 PHP 中,數(shù)組是一種廣泛應(yīng)用的數(shù)據(jù)結(jié)構(gòu),而 JSON(JavaScript Object Notation)是一種輕量級的數(shù)據(jù)格式,常用于在 Web 應(yīng)用程序中傳輸數(shù)據(jù)。了解如何將 PHP 數(shù)組快速轉(zhuǎn)換為 JSON 非常重要。
立即學(xué)習(xí)“PHP免費學(xué)習(xí)筆記(深入)”;
JSON_encode() 函數(shù)
最簡單的方法是使用 json_encode() 函數(shù),它接受一個 PHP 數(shù)組并將其轉(zhuǎn)換為 JSON 字符串:
$array = ['name' => 'John Doe', 'age' => 30]; $json = json_encode($array); echo $json; // 輸出:{"name":"John Doe","age":30}
json_decode() 函數(shù)
為了執(zhí)行相反的操作(從 JSON 字符串轉(zhuǎn)換為 PHP 數(shù)組),可以使用 json_decode() 函數(shù):
$json = '{"name":"John Doe","age":30}'; $array = json_decode($json, true); var_dump($array); // 輸出:array(2) { ["name"]=> string(7) "John Doe" ["age"]=> int(30) }
傳遞 true 作為第二個參數(shù)可將 JSON 對象轉(zhuǎn)換為關(guān)聯(lián)數(shù)組,而不是對象。
其他技巧
實戰(zhàn)案例
考慮一個用戶數(shù)據(jù) API,該 API 需要將用戶數(shù)據(jù)從數(shù)據(jù)庫轉(zhuǎn)換為 JSON 格式,以通過 AJAX 發(fā)送到前端。
// 從數(shù)據(jù)庫獲取用戶數(shù)據(jù) $users = $db->select('users', '*'); // 創(chuàng)建用戶數(shù)組 $user_array = []; foreach ($users as $user) { $user_array[] = [ 'id' => $user['id'], 'name' => $user['name'], 'email' => $user['email'] ]; } // 轉(zhuǎn)換數(shù)組為 JSON $json = json_encode($user_array); // 返回 JSON 響應(yīng) header('Content-Type: application/json'); echo $json;
該腳本從數(shù)據(jù)庫中檢索用戶數(shù)據(jù),并使用 json_encode() 將其轉(zhuǎn)換為 JSON 字符串。然后將 JSON 響應(yīng)返回給前端。
以上就是PHP 數(shù)組轉(zhuǎn) JSON 的快捷技巧的詳細內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
PHP怎么學(xué)習(xí)?PHP怎么入門?PHP在哪學(xué)?PHP怎么學(xué)才快?不用擔(dān)心,這里為大家提供了PHP速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號