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 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥15 pyqt怎么把滑块和输入框相互绑定,求解决!
  • ¥20 wpf datagrid单元闪烁效果失灵