練習各種php資訊轉為json格式寫法

<?php
class Obj1 {
    public $iData = 100;
    public $bData = true;
    public $sData = 'sssssss';
    public $name = 'Obj1';
}
#echo "Post data:".$_POST["var1"];
#echo "Post data:".$_POST["var2"];
$data['result'] = true;
$json = json_encode($data);

#$data['var1'] = $_POST["var1"];
#$data['var2'] = $_POST["var2"];
#$json = json_encode($data);

//add item
$data['msg'] = "xxxx";
$json = json_encode($data);

$data['int'] = 100;
$json = json_encode($data);

$data['float'] = 77.77;
$json = json_encode($data);

$data['bool'] = false;
$json = json_encode($data);

//add array
$ar = array('apple', 'orange', 'banana', 'strawberry');
$data['fruit'] = $ar;
$json = json_encode($data);

//add dic
$arr1=array('key'=>'value','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
$data['Dic'] = $arr3;
$json = json_encode($data);

//add one obj
$a = new Obj1();
$data['Class'] = $a;
$json = json_encode($data);

$b = new Obj1();
$b->iData = 200;
$b->bData = false;
$b->sData = 'bbbbb';
$b->bData = 'bName';

//add class array
$car = array($a, $b);
$data['class_array'] = $car;
$json = json_encode($data);

$map1=array('key1'=>$a,'key2'=>$b); 
$data['Map1'] = $map1;
$json = json_encode($data);

$map2=array(100=>$a,200=>$b); 
$data['Map2'] = $map2;
$json = json_encode($data);

//add array use map
$map3=array('key3'=>$a,'key4'=>$b); 
$test = array($map1, $map2);
$data['AMap'] = $test;
$json = json_encode($data);

echo $json;
?>

 

輸出如下:

{"result":true,"msg":"xxxx","int":100,"float":77.77,"bool":false,"fruit":["apple","orange","banana","strawberry"],"Dic":[{"key":"value","result2":"efg"},{"result1":"hijk","result2":"lmn"}],"Class":{"iData":100,"bData":true,"sData":"sssssss","name":"Obj1"},"class_array":[{"iData":100,"bData":true,"sData":"sssssss","name":"Obj1"},{"iData":200,"bData":"bName","sData":"bbbbb","name":"Obj1"}],"Map1":{"key1":{"iData":100,"bData":true,"sData":"sssssss","name":"Obj1"},"key2":{"iData":200,"bData":"bName","sData":"bbbbb","name":"Obj1"}},"Map2":{"100":{"iData":100,"bData":true,"sData":"sssssss","name":"Obj1"},"200":{"iData":200,"bData":"bName","sData":"bbbbb","name":"Obj1"}},"AMap":[{"key1":{"iData":100,"bData":true,"sData":"sssssss","name":"Obj1"},"key2":{"iData":200,"bData":"bName","sData":"bbbbb","name":"Obj1"}},{"100":{"iData":100,"bData":true,"sData":"sssssss","name":"Obj1"},"200":{"iData":200,"bData":"bName","sData":"bbbbb","name":"Obj1"}}]}

請使用http://json.parser.online.fr 來查看json結構

, , , ,

狼翔月影 發表在 痞客邦 PIXNET 留言(0) 人氣()