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"';
2 Answers 2
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"}}}
1 Comment
var somevar = <?php echo json_encode($settings);?>;alert(somevar.customer.first_name);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
json_encode().json_encode?