如何将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"
];

当前回答

Spudley的回答很好。

安全通知:您应该不再需要以下内容

如果你没有PHP 5.2,你可以使用这样的东西:

function js_str($s)
{
    return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}

function js_array($array)
{
    $temp = array_map('js_str', $array);
    return '[' . implode(',', $temp) . ']';
}

echo 'var cities = ', js_array($php_cities_array), ';';

其他回答

可以用更安全的方式来做。

如果你的PHP数组包含特殊字符,你需要在PHP中使用rawurlencode(),然后在JS中使用decodeURIComponent()来转义这些字符。并将JSON解析为原生js。试试这个:

var data = JSON.parse(
        decodeURIComponent(
            "<?=rawurlencode(json_encode($data));?>"
        )
    );

console.log(data);

我使用了一个伪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>

如果您需要将多维PHP数组直接打印到html页面源代码中,并以一种缩进的人类可读的Javascript对象符号(又名JSON)方式,请使用我在http://php.net/manual/en/function.json-encode.php#102091中找到的这个由绰号为“bohwaz”的人编写的漂亮函数。

<?php

function json_readable_encode($in, $indent = 0, $from_array = false)
{
    $_myself = __FUNCTION__;
    $_escape = function ($str)
    {
        return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
    };

    $out = '';

    foreach ($in as $key=>$value)
    {
        $out .= str_repeat("\t", $indent + 1);
        $out .= "\"".$_escape((string)$key)."\": ";

        if (is_object($value) || is_array($value))
        {
            $out .= "\n";
            $out .= $_myself($value, $indent + 1);
        }
        elseif (is_bool($value))
        {
            $out .= $value ? 'true' : 'false';
        }
        elseif (is_null($value))
        {
            $out .= 'null';
        }
        elseif (is_string($value))
        {
            $out .= "\"" . $_escape($value) ."\"";
        }
        else
        {
            $out .= $value;
        }

        $out .= ",\n";
    }

    if (!empty($out))
    {
        $out = substr($out, 0, -2);
    }

    $out = str_repeat("\t", $indent) . "{\n" . $out;
    $out .= "\n" . str_repeat("\t", $indent) . "}";

    return $out;
}

?>       

愚蠢而简单:

var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];

保持简单:

var jsObject = JSON.parse('<?= addslashes(json_encode($phpArray)) ?>');