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"';
4
  • Did you try searching for this? Commented Feb 27, 2014 at 1:20
  • See updated, it is not as simple as json_encode(). Commented Feb 27, 2014 at 1:23
  • Can you explain a little more about why this approach is necessary over json_encode? Commented Feb 27, 2014 at 1:28
  • What you're trying to do is a terrible idea and makes no sense. Commented Feb 27, 2014 at 1:29

2 Answers 2

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"}}}
Sign up to request clarification or add additional context in comments.

1 Comment

@justin I think you will find it works like: var somevar = <?php echo json_encode($settings);?>;alert(somevar.customer.first_name);
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.