Home > Backend Development > PHP Tutorial > php怎么格式化字符串

php怎么格式化字符串

WBOY
Release: 2016-06-13 10:34:48
Original
1257 people have browsed it

php如何格式化字符串
有数据库字段如下:
name sum
张三 20
李四 30
王五 11
麻子 12

想从数据库读出数据并格式化成以下格式:
var myData =new Array(['张三',20],['李四',30],['王五',11],['麻子',12]);

在C#里面有format 和stringbuilder函数很容易实现,不知道在PHP里面有类似的函数吗,欢迎贴代码

------解决方案--------------------

PHP code
$data = array(    array('张三', 20),    array('李四', 30),    array('王五', 11),    array('麻子', 12));$str = '';foreach ($data as $arr) {    $str .= ",['{$arr[0]}', {$arr[1]}]";}//echo ltrim($str, ',');// ['张三', 20],['李四', 30],['王五', 11],['麻子', 12]$myData = "var myData =new Array($str);";//echo $myData;// var myData =new Array(,['张三', 20],['李四', 30],['王五', 11],['麻子', 12]);<br><font color="#e78608">------解决方案--------------------</font><br>直接json_encode($mydate);就好了,就是json格式的<br><font color="#e78608">------解决方案--------------------</font><br>
Copy after login
PHP code
$data = array(    array('张三', 20),    array('李四', 30),    array('王五', 11),    array('麻子', 12));echo json_encode($data);<div class="clear">
                 
              
              
        
            </div>
Copy after login
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