如何将PHP数组转换成这样的格式
Array
(
[0] => 001-1234567
[1] => 1234567
[2] => 12345678
[3] => 12345678
[4] => 12345678
[5] => AP1W3242
[6] => AP7X1234
[7] => AS1234
[8] => MH9Z2324
[9] => MX1234
[10] => TN1A3242
[11] => ZZ1234
)
到下面格式的Javascript数组?
var cities = [
"Aberdeen",
"Ada",
"Adamsville",
"Addyston",
"Adelphi",
"Adena",
"Adrian",
"Akron",
"Albany"
];
我使用了一个伪php数组
<?php
// instead to create your array like this
$php_array = ["The","quick","brown","fox","jumps","over","the","lazy","dog"];
// do it like this (a simple variable but with separator)
$php_fake_array = "The,quick,brown,fox,jumps,over,the,lazy,dog";
?>
<script type="text/javascript">
// use the same separator for the JS split() function
js_array = '<?php echo $php_fake_array; ?>'.split(',');
</script>
如果你的数组是未知的(已经创建)
<?php
$php_array = file('my_file.txt');
$php_fake_array = "";
// transform your array with concatenate like this
foreach ($php_array as $cell){
// since this array is unknown, use clever separator
$php_fake_array .= $cell.",,,,,";
}
?>
<script type="text/javascript">
// use the same separator for the JS split() function
js_array = '<?php echo $php_fake_array; ?>'.split(',,,,,');
</script>
这里有许多好的和复杂的解决方案,这是一种不需要在用户端解析json的方法。
$mtc=array();
$replace=array();
$x = json_encode($thearray);
preg_match_all('/"[a-z0-9_]*":/',$x,$mtc);
foreach($mtc[0] as $v){
array_push($replace,str_replace('"','',$v));
}
$x = str_replace($mtc[0],$replace,$x);
echo '<script type="text/javascript">x='.$x.';console.log(x);</script>';
这适用于具有多个级别的索引数组和关联数组(任何组合),并且不需要用户端json解析。