JSON [PHP]

php

2009-07-27 11:44

json_encode                         json_decode                   这个函数仅在UTF-8编码格式时起作用


<?
$B = array("id"=>"1","name"=>"windy","age"=>"24","chinese"=>"xxxxxx","addressId"=>"xxxxxxx");
$json = json_encode($B);   //数组转换JSON格式 j
echo $json;

echo "<p>";

$A=json_decode($json);         //JSON格式转换对象   $A->id
$A=json_decode($json,true); //JSON格式转换数组   $A['id']


?>

{"id":"1","name":"windy","age":"24","chinese":null,"addressId":null}

{ ["id"]=> string(1) "1" ["name"]=> string(5) "windy" ["age"]=> string(2) "24" ["chinese"]=> NULL ["addressId"]=> NULL }




$j.get("url.php", {addressId:obj.value, type:type}, function(res) {
                                    eval("var data=" + res + "");
                                     if (!data) return;
                                       $j("#addressId").val(data.addressId);
                                        $j("#id").val(data.id);
                                        $j("#name").val(data.name);
                                        $j("#age").val(data.age);
                                        $j("#chinese").val(data.chinese);
}

实例演示:

<?php
$arr = array( 'name' => 'menzhi007',    
      'sex' => 'man',    
      'contact' => array(         
       'email' => 'xxxx@qq.com,      
       'QQ' => '88888',   
       'Blog' => 'http://hi.baidu.com/000001',
         )
);
$json_string = json_encode($arr);
//$decode = json_decode($json_string);
//print_r ($decode);
?>

<script>
var arr =<?php echo "$json_string"; ?>;
//alert(arr.name);
document.write(arr.name);
document.write(arr.contact.email);
</script>