将PHP多维数组转换为JavaScript表示法

时间:2014-02-27 01:17:57

标签: javascript php json

我正在寻找一种高效且干净的功能,将PHP多维数组转换为javascript表示法定义。例如:

$settings = array(
    "customer" => array(
        "first_name" => "John",
        "last_name" => "Doe",
        "company" => array(
            "name" => "Foobar Inc",
            "address" => "123 Main Street"
        )
    )
)

应转化为:

echo 'window.customer.first_name = "John"';
echo 'window.customer.last_name = "Doe"';
echo 'window.customer.company.name = "Foobar Inc"';
echo 'window.customer.company.address = "123 Main Street"';

2 个答案:

答案 0 :(得分:5)

只需使用json_encode()

即可
$json = json_encode($settings);

示例:

$settings = array(
    "customer" => array(
        "first_name" => "John",
        "last_name" => "Doe",
        "company" => array(
            "name" => "Foobar Inc",
            "address" => "123 Main Street"
        )
    )
);

echo json_encode($settings);

<强>输出

{"customer":{"first_name":"John","last_name":"Doe","company":{"name":"Foobar Inc","address":"123 Main Street"}}}

答案 1 :(得分:0)

看起来您正在尝试生成.ini文件。我会说你可以编写一个简单的递归函数,给定一个用作属性名称开头的基本字符串,然后为它的值生成一行输出 - 或者一系列行,递归调用自身,如果value是一个数组。

此处给出了另一种方法:create ini file, write values in PHP