Home  >  Article  >  Backend Development  >  Convert php array to js array

Convert php array to js array

藏色散人
藏色散人Original
2021-03-26 10:34:002479browse

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');
    }

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>

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>

Convert php array to js array

Method 2:

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

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!

Statement:
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
Previous article:How to install iis php5.2Next article:How to install iis php5.2