將 json 賦給 php 變量的方法包括:使用 json_decode() 函數(shù)將 json 字符串轉(zhuǎn)換為 php 數(shù)組。通過(guò)將 json_decode() 函數(shù)的第二個(gè)參數(shù)設(shè)置為 false,可以將 json 字符串轉(zhuǎn)換為 php 對(duì)象。可以通過(guò)數(shù)組或?qū)ο蟮膶傩栽L問(wèn)已分配給 php 變量的 json 數(shù)據(jù)。
如何將 JSON 賦給 PHP 變量
賦值方法
要將 JSON 字符串賦給 PHP 變量,可以使用以下方法:
使用 json_decode() 函數(shù)
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
$json_string = '{"name": "John Doe", "age": 30}'; $json_data = json_decode($json_string);
關(guān)注:愛(ài)掏網(wǎng)
JSON 數(shù)組
通過(guò) json_decode() 函數(shù),JSON 字符串可以轉(zhuǎn)換為 PHP 數(shù)組:
$json_array = json_decode($json_string, true);
關(guān)注:愛(ài)掏網(wǎng)
JSON 對(duì)象
將 JSON 字符串轉(zhuǎn)換為 PHP 對(duì)象時(shí),需要使用 json_decode() 函數(shù)的第二個(gè)參數(shù)為 false:
$json_object = json_decode($json_string, false);
關(guān)注:愛(ài)掏網(wǎng)
訪問(wèn) JSON 數(shù)據(jù)
分配給 PHP 變量的 JSON 數(shù)據(jù)可以直接通過(guò)數(shù)組或?qū)ο蟮膶傩赃M(jìn)行訪問(wèn):
// 訪問(wèn) name 屬性 echo $json_data->name; // John Doe // 訪問(wèn) age 屬性 echo $json_array['age']; // 30
關(guān)注:愛(ài)掏網(wǎng)
以上就是php如何將json賦給變量的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注愛(ài)掏網(wǎng) - it200.com其它相關(guān)文章!
聲明:所有內(nèi)容來(lái)自互聯(lián)網(wǎng)搜索結(jié)果,不保證100%準(zhǔn)確性,僅供參考。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進(jìn)行處理。