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.
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:
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>
Method 2:
<script type="text/javascript">var arr = <?php echo json_encode($data);?>;console.log(arr);</script>
Use directly in php json encoded 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!