Converting Data Formats Between PHP Arrays and JSON
Recently, I have been developing an API interface for a short URL service, so I read many articles about APIs. The technology used most commonly is JSON. JSON, also known as JavaScript Object Notation, is a lightweight data-interchange format. Since PHP is the language I use for API development, I need to use the interaction between JSON and PHP during data processing—that is, data conversion.

Below, I will mainly introduce two ways to convert between JSON and arrays.
json_encode()
Because JSON only accepts characters encoded in UTF-8, the argument to json_encode() must be UTF-8 encoded; otherwise, an empty string or null will be returned. This point requires special attention when Chinese uses GB2312 encoding!
Example 1 (Array)
<?php
$array_a =array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($array_a);
?>
Output
{"a":1,"b":2,"c":3,"d":4,"e":5}
Example 2 (Object)
<?php
$obj->body = 'another post';
$obj->id = 21;
$obj->approved = true;
$obj->favorite_count = 1;
$obj->status = NULL;
echo json_encode($obj);
?>
Output
{
"body":"another post",
"id":21,
"approved":true,
"favorite_count":1,
"status":null
}
json_decode()
This function is used to convert JSON text into the corresponding PHP data structure. Under normal circumstances, json_decode() always returns a PHP object rather than an array.
Example 3
<?php
$json ='{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
Output
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
If you want to force the generation of a PHP associative array, you need to add a true argument to json_decode().
Example 4
<?php
$json ='{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));
?>
Output
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
In addition, JSON can only be used to represent objects and arrays. Using json_decode() on a string or numeric value will return null.
Comments
(0)No comments yet. Start the conversation.