Convert php array to js array

藏色散人
Release: 2023-03-09 06:50:02
Original
2562 people have browsed it

How to convert php array to js array: 1. Convert $data into json encoding, and then use eval to convert the json format into js array; 2. Directly use the json encoded array in php.

Convert php array to js array

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

Convert php array to js array

Method 1:

In the controller:

	public function index()
    {
        $sql=Db::name('shuju')
            ->field('name')
            ->select();
        foreach($sql as $val)
        {
            $arr[]=$val['name'];
        }
        $this->assign('data',$arr);
        return $this->fetch('index');
    }
Copy after login

Look at it What kind of array is $arr:
Convert php array to js array
In the view:

<html>  <head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <title></title> 
    <script src="__STATIC__/js/jquery-3.3.1.min.js"></script> 
    <script type="text/javascript" src="__STATIC__/js/layer/layer.js"></script></script>  </head>  <body><script type="text/javascript">var arr = eval(<?php echo json_encode($data);?>);console.log(arr);</script> </body>  </html>
Copy after login

First convert $data into json encoding, and then use eval to convert the json format into js array

<script type="text/javascript">var arr = eval(<?php echo json_encode($data);?>);console.log(arr);</script>
Copy after login

Convert php array to js array

Method 2:

<script type="text/javascript">var arr = <?php echo json_encode($data);?>;console.log(arr);</script>
Copy after login

Use directly in php json encoded array

Convert php array to js array

[Recommended learning: PHP video tutorial]

The above is the detailed content of Convert php array to js array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!