An analysis of arrays in PHP and arrays in JS

Source: Internet
Author: User

Recently in the front-end docking, encountered a problem, the front-end required to return the data format is left, but I returned through the Json_encode data format is the right Note: The data format from "[]" (array) into "{}" (object)

Google, found that: JavaScript does not support associative arrays, PHP indexed array into JSON is an array ([]), the PHP associative array to JSON is an object ({}), so if it is an associative array, you need to do some processing of arrays

Arrays in PHP: indexed arrays and associative arrays

PHP supports two arrays, one is an indexed array (indexed array) that only holds "value", and the other is an associative array (associative array) that holds "name value pairs" (name/value).

Because JavaScript does not support associative arrays, json_encode () only converts an indexed array (indexed array) into an array format, and the associative array (associative array) to the object format.

For example:

// 1. Indexed array $arr Array (' One ', ' both ', ' three '); echo json_encode ($arr); // return Value:
// 2. Associative Arrays $arr Array (' 1 ' = ' one ', ' 2 ' = '-'-', ' 3 ' = ' three '); echo json_encode ($arr); // return Result:

Therefore, if you need to achieve the result of figure one, we need to process the associative array in our array (to an indexed array)

Recommend a function:

Array_values (): Returns all values of the array (non-key names)
$a=array("Name" = "Bill", "age" = "all", "country" = "USA"); Print_r (array_values($a)); // return Results Array ([0] = Bill [1] [2] = USA)

Finally, after the Json_encode processing, it will reach the result of Figure I.

Above

An analysis of arrays in PHP and arrays in JS

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.