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":"[email protected]","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":"[email protected]","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":"[email protected]","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;
}
?>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章