日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

PHP JSON 操作总结

發布時間:2025/3/20 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 PHP JSON 操作总结 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文:PHP JSON 操作總結

? ? ? ?由于JSON可以在很多種程序語言中使用,所以我們可以用來做小型數據中轉,如:PHP輸出JSON字符串供JavaScript使用等。在PHP中可以使用 json_decode() 由一串規范的字符串解析出 JSON對象,使用 json_encode() 由JSON 對象生成一串規范的字符串。

例:<?php

$json = '{"a":1, "b":2, "c":3, "d":4, "e":5 }';

var_dump(json_decode($json));

var_dump(json_decode($json,true));

輸出:

object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}

array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);

輸出:{"a":1,"b":2,"c":3,"d":4,"e":5}

1. json_decode(),字符轉JSON,一般用在接收到Javascript 發送的數據時會用到。

<?php
$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
$web=json_decode($s);
echo '網站名稱:'.$web->webname.'<br />網址:'.$web->url.'<br />聯系方式:QQ-'.$web->contact->qq.'&nbsp;MAIL:'.$web->contact->mail;
?>

上面的例子中,我們首先定義了一個變量s,然后用json_decode()解析成JSON對象,之后可以按照JSON的方式去使用,從使用情況看,JSON和XML以及數組實現的功能類似,都可以存儲一些相互之間存在關系的數據,但是個人覺得JSON更容易使用,且可以使用JSON和JavaScript實現數據共享。

2. json_encode(),JSON轉字符,這個一般在AJAX 應用中,為了將JSON對象轉化成字符串并輸出給 Javascript 時會用到,而向數據庫中存儲時也會用到。

<?php
$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
$web=json_decode($s);
echo json_encode($web);
?>

二 .PHP JSON 轉數組

<?php
$s='{"webname":"homehf","url":"www.homehf.com","qq":"744348666"}';
$web=json_decode($s); //將字符轉成JSON
$arr=array();
foreach($web as $k=>$w) $arr[$k]=$w;
print_r($arr);
?>

上面的代碼中,已經將一個JSON對象轉成了一個數組,可是如果是嵌套的JSON,上面的代碼顯然無能為力了,那么我們寫一個函數解決嵌套JSON,


<?php
$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';
$web=json_decode($s);
$arr=json_to_array($web);
print_r($arr);

function json_to_array($web){
$arr=array();
foreach($web as $k=>$w){
??? if(is_object($w)) $arr[$k]=json_to_array($w); //判斷類型是不是object
??? else $arr[$k]=$w;
}
return $arr;
}
?>

?

總結

以上是生活随笔為你收集整理的PHP JSON 操作总结的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。