A multidimensional array Json_encode after an object is generated instead of an array __js

Source: Internet
Author: User

The Json_encode function can encode an array of PHP, and the return value is a JSON-formatted string.


For multidimensional arrays to Json_encode, I always thought it was a return array form (like {{obj1}, {obj2}, {obj3}}), but today the interface is returned to the client discovery as an object rather than an array (in the form of [{... ...},{.....},{...}] ), not convenient for client operation, check the code only to find that I previously a unset operation to the multidimensional array of the first unit to delete, resulting in a different return results.


Look at the code below:


$arr = Array (
<span style= "White-space:pre" >	</span>0=>array (' name ' => ' John ', ' age ' => ') ),
<span style= "White-space:pre" >	</span>1=>array (' name ' => ' Dick ', ' age ' => ' 111 '),
<span style= "White-space:pre" >	</span>2=>array (' name ' => ' Harry ', ' Age ' => ' 233 ')
);


$res = Json_encode ($arr);
echo "<script>console.log (' $res ');</script>";
The results are as follows:


Then look after the first index is removed:

$arr = Array (
	0=>array (' name ' => ' John ', ' Age ' => ' "),
	1=>array (' name ' => ' Dick ', ' age ' => ' 111 ') ,
	2=>array (' name ' => ' Harry ', ' Age ' => ' 233 ')
);

unset ($arr [0]); 
$res = Json_encode ($arr);
echo "<script>console.log (' $res ');</script>";

The solution is to use the Sort function to index again.


$arr = Array (
	0=>array (' name ' => ' John ', ' Age ' => ' "),
	1=>array (' name ' => ' Dick ', ' age ' => ' 111 ') ,
	2=>array (' name ' => ' Harry ', ' Age ' => ' 233 ')
);

unset ($arr [0]); 
Sort ($arr);
$res = Json_encode ($arr);
echo "<script>console.log (' $res ');</script>";



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.