萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> json_encode() 和 json_decode() 實例

json_encode() 和 json_decode() 實例

/*
json_encode - 返回一個值的JSON格式數組
json_encode — Returns the JSON representation of a value


*/


$arr = array ('a'=>"www.111cn.net",'b'=>"cc",'c'=>3,'d'=>4,'e'=>5);

$carray = json_encode($arr);

echo $carray ;

//結果{"a":"www.111cn.net","b":"cc","c":3,"d":4,"e":5} 現在我們用json_decode

$array = json_decode ( $carray );

print_r( $array );

/*
 結果
 (
    [a] => www.111cn.net
    [b] => cc
    [c] => 3
    [d] => 4
    [e] => 5
 )
*/

//隨著字符串鍵PHP將考慮它的一個對象:


echo json_encode(array('id'=>'www.111cn.net'));
echo json_encode(array('testtext'));

/*
{"id":"www.111cn.net"}
["testtext"]

一個輸出json格式的函數
*/

 代碼如下 復制代碼

function json_format($json)
{
    $tab = "  ";
    $new_json = "";
    $indent_level = 0;
    $in_string = false;
   
    $json_obj = json_decode($json);
   
    if(!$json_obj)
        return false;
   
    $json = json_encode($json_obj);
    $len = strlen($json);
   
    for($c = 0; $c < $len; $c++)
    {
        $char = $json[$c];
        switch($char)
        {
            case '{':
            case '[':
                if(!$in_string)
                {
                    $new_json .= $char . " " . str_repeat($tab, $indent_level+1);
                    $indent_level++;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '}':
            case ']':
                if(!$in_string)
                {
                    $indent_level--;
                    $new_json .= " " . str_repeat($tab, $indent_level) . $char;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ',':
                if(!$in_string)
                {
                    $new_json .= ", " . str_repeat($tab, $indent_level);
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ':':
                if(!$in_string)
                {
                    $new_json .= ": ";
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '"':
                $in_string = !$in_string;
            default:
                $new_json .= $char;
                break;                   
        }
    }
   
    return $new_json;
}

/*


在用到json_encode這個函數注意,它不支持中文,所以我們要先把編輯urlencode編輯再在js轉,並且js返回的數據給php教程時也要注意一點,json返回的數據是utf-8的如果你的php文檔是gbk的,所以也要用incov轉換成gbk哦。
*/

copyright © 萬盛學電腦網 all rights reserved