1

I am looking for an efficient and clean function to convert PHP multidimensional arrays to javascript notation definitions. For example:

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

Should translate into:

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"';
Justin
  • 42,716
  • 77
  • 201
  • 296

2 Answers2

5

Just use json_encode()

$json = json_encode($settings);

Example:

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

echo json_encode($settings);

Output:

{"customer":{"first_name":"John","last_name":"Doe","company":{"name":"Foobar Inc","address":"123 Main Street"}}}
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • @justin I think you will find it works like: `var somevar = ;alert(somevar.customer.first_name);` – Scuzzy Feb 27 '14 at 01:38
0

It looks like you're trying to generate an .ini file. I'd say you could write a simple recursive function that, given a base string to use as the start of the property name, would then generate a line of output for its value - or a sequence of lines, recursively calling itself, if the value is an array.

Another approach is given here: create ini file, write values in PHP

Community
  • 1
  • 1
Brian Kendig
  • 2,452
  • 2
  • 26
  • 36