如何将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>

其他回答

我发现在Javascript中使用PHP数组的最快和最简单的方法是这样做:

PHP:

$php_arr = array('a','b','c','d');

Javascript:

//this gives me a JSON object
js_arr = '<?php echo JSON_encode($php_arr);?>';


//Depending on what I use it for I sometimes parse the json so I can work with a straight forward array:
js_arr = JSON.parse('<?php echo JSON_encode($php_arr);?>');

这么简单…!

使用这个方法:

<?php echo json_encode($your_array); ?>; 

在laravel blade{{}}中使用以下方法:

{{ str_replace('&quot;', '', json_encode($your_array)) }} 

为关联和非关联数组工作。

对于Laravel用户:使用@json

var cities = @json($data);

官方文档中有解释:https://laravel.com/docs/8.x/blade#rendering-json:

这里有许多好的和复杂的解决方案,这是一种不需要在用户端解析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解析。

对于Laravel, Blade{{}}语句通过PHP的htmlspecialchars函数自动发送,以防止XSS攻击。你的数据是不转义的,你可以使用以下语法:

const jsArray = {!! str_replace('&quot;', '', json_encode($array)) !!};