douwei8911 2011-04-11 08:54
浏览 65
已采纳

将php数组转换为Javascript

How can I convert a PHP array in a format like this

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
)

to a Javascript array in the format below?

var cities = [
    "Aberdeen",
    "Ada",
    "Adamsville",
    "Addyston",
    "Adelphi",
    "Adena",
    "Adrian",
    "Akron",
    "Albany"
];
  • 写回答

16条回答 默认 最新

  • doujingjiao0015 2011-04-11 09:18
    关注

    Spudley's answer is fine.

    Security Notice: The following should not be necessary any longer for you

    If you don't have PHP 5.2 you can use something like this:

    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), ';';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(15条)

报告相同问题?

悬赏问题

  • ¥15 信号发生器如何将频率调大,步尽值改成10
  • ¥15 keil 5 编程智能家具,风扇台灯开关,人体感应等
  • ¥100 找一名渗透方面的专家
  • ¥20 使用Matlab gui设计一个插补小程序
  • ¥15 evo评估时曲线出现问题
  • ¥15 eNSP拓扑图配置实验
  • ¥20 有没有兄弟会替换fmod studio的.bank文件内的音效?
  • ¥20 如何解决访问网址被屏蔽的情况
  • ¥20 powerbuilder datawindow控件导出Excel数据,可不可以不自动覆盖原数据,而是在后面新插入入数据。
  • ¥15 telegram 问题