This article is mainly to illustrate the use of json_encode a need to pay attention to the details, whether the return of the array or JSON, does not mean that this must be a wrong return, the current side needs an array, the array is the correct result, and vice versa
In today's Ajax-infested world, JSON logically becomes an extremely important tool for front-to-back interaction. For PHP, it is common to use the Json_encode method to convert a PHP group to a JSON string that can be parsed by the front end, which is what is described in the PHP manual, but is it true? Take a look at the following code:
The code is as follows:
$a = Array (' Jack ', ' Sam ', ' Tom ');
echo Json_encode ($a);
When JavaScript requests the code above, PHP parses the array $a as a JSON string and returns to the front end, but in fact the return result in the front end is an array.
The code is as follows:
["Jack", "Sam", "Tom"]
This result may not be desirable for the front end, and for JavaScript, arrays are very closely related to JSON, and even JSON can be simply understood as associative arrays, but this does not mean that they can be equated, such as JSON without the length property, Also cannot be a numeric index, JSON is a key-value pair, and JavaScript arrays strictly speaking there is no "key", which differs from PHP is relatively large. So why is the return of Json_encode an array?
The array in the PHP code at the beginning of this article is a strictly numeric index array, and the Json_encode method returns an array string when dealing with such an array, which needs to satisfy two conditions simultaneously: 1. Numeric index array, 2. The index value starts at 0. This means that the following code will return the same result:
The code is as follows:
$b = Array (
' 0 ' = ' Jack ',
' 1 ' = ' Sam ',
' 2 ' = ' Tom '
);
echo Json_encode ($b);
Any one of these two conditions is not satisfied, then the Json_encode method actually returns the JSON string:
The code is as follows:
$c = Array (
' person-1 ' = ' Jack ',
' Person-2 ' = ' Sam ',
' person-3 ' = ' Tom '
);
echo Json_encode ($c);
The results from the front end are as follows:
The code is as follows:
{
' person-1 ': ' Jack ',
' Person-2 ': ' Sam ',
' person-3 ': ' Tom '
};
http://www.bkjia.com/PHPjc/750626.html www.bkjia.com true http://www.bkjia.com/PHPjc/750626.html techarticle This article is mainly to illustrate the use of json_encode a need to pay attention to the details, whether the return of the array or JSON, does not mean that this must be a wrong return results, the current end needs ...