PHP中json_encode()和json_decode

json_encode () to encode variable JSON

You need to know is:

  • json data is actually a string, you can () print out to see the type of data used var_dump;
  • Implementation of successful return json data, false otherwise
    for example:
$book = array('a'=>'xiyouji','b'=>'sanguo','c'=>'shuihu','d'=>'hongloumeng');
$json = json_encode($book);
echo $json
//{"a":"xiyouji","b":"sanguo","c":"shuihu","d":"hongloumeng"}

of json_decode () to json data is encoded, converted to a variable php

Syntax: json_decode ($ json [, $ assoc = false [, $ depth = 512 [, $ option = 0]]])
NOTE:

  • $ JSON data to be decoded, the coded data must utf8
  • When the return value is an array of true $ assoc, returns false if the object
  • $ Depth for the recursion depth
  • $ Option binary mask, currently only supports JSON_BIGINT_AS_STRING;
  • Usually only the first two parameters, if you want to add a data type parameter set to true
    , for example:
$book = array('a'=>'xiyouji','b'=>'sanguo','c'=>'shuihu','d'=>'hongloumeng');
	$json = json_encode($book);

	$array = json_decode($json,TRUE);
	$obj = json_decode($json);
	var_dump($array);
	//array(4) {["a"]=>string(7)"xiyouji" ["b"]=>string(6) "sanguo" ["c"]=> string(6) "shuihu" ["d"]=>string(11) "hongloumeng"}
	var_dump($obj);
	//object(stdClass) #2 (4)  {["a"]=>string(7)"xiyouji" ["b"]=>string(6) "sanguo" ["c"]=> string(6) "shuihu" ["d"]=>string(11) "hongloumeng"}

The result looks not much difference between the two, but when calling inside the element, array and obj is a different way of
example:

$book = array('a'=>'xiyouji','b'=>'sanguo','c'=>'shuihu','d'=>'hongloumeng');
        $json = json_encode($book);
        
        $array = json_decode($json,TRUE);
        $obj = json_decode($json);
        var_dump($array['b']);//调用数组元素
        echo '<br/>';
        var_dump($obj->c);//调用对象元素
        //string(6) "sanguo"
		//string(6) "shuihu" 

Guess you like

Origin blog.csdn.net/qq_42216575/article/details/90029826