How to assign values to js arrays in php

Source: Internet
Author: User

Because the interface requires processing data in js, the php program needs to retrieve the value from the database and assign the value to the js array. We have never found a good solution because the data encoding format of PHP arrays is different from that of JS arrays and cannot be directly output.

After searching for a message on the Internet, find the solution:

The PHP function library provides JSON encoding/decoding functions: json_encode () and json_decode (), which can easily pass arrays or objects to javascript. Note: PHP 5.2 and later versions are bound with JSON extensions.

Write in php as follows:
Copy codeThe Code is as follows:
$ Arr = array ('1', array ('2', '3'), array ('new', 'old '));
$ New_arr = json_encode ($ arr); // The output result of new_arr is: ["1", ["2", "3"], ["new ", "old"]
Echo "var data =". $ new_arr;

After referencing the above PHP file on the page, you can directly operate on data in js.

Related Article

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.