您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)如何將PHP數(shù)組轉(zhuǎn)換成JSON,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
在PHP中可以通過使用函數(shù)“json_encode()”將數(shù)組轉(zhuǎn)為JSON,該函數(shù)的作用是對(duì)變量進(jìn)行JSON編碼,函數(shù)語法為“json_encode($val)”,返回值為JSON編碼的字符串。
使用示例
<?php $a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9"); echo "Normal: ", json_encode($a), "\n"; echo "Tags: ", json_encode($a, JSON_HEX_TAG), "\n"; echo "Apos: ", json_encode($a, JSON_HEX_APOS), "\n"; echo "Quot: ", json_encode($a, JSON_HEX_QUOT), "\n"; echo "Amp: ", json_encode($a, JSON_HEX_AMP), "\n"; echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n"; echo "All: ", json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n"; $b = array(); echo "Empty array output as array: ", json_encode($b), "\n"; echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n"; $c = array(array(1,2,3)); echo "Non-associative array output as array: ", json_encode($c), "\n"; echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n"; $d = array('foo' => 'bar', 'baz' => 'long'); echo "Associative array always output as object: ", json_encode($d), "\n"; echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n"; ?> 以上例程會(huì)輸出: Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"] Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"] Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"] Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"] Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"] Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"] All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"] Empty array output as array: [] Empty array output as object: {} Non-associative array output as array: [[1,2,3]] Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}} Associative array always output as object: {"foo":"bar","baz":"long"} Associative array always output as object: {"foo":"bar","baz":"long"}
看完上述內(nèi)容,你們對(duì)如何將PHP數(shù)組轉(zhuǎn)換成JSON有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。