I'm creating a Wordpress Plugin which uses a jQuery script. I've created a PHP array which contains its options like:
$settings = array('setting1' => 'value1', 'setting2' => 'valu开发者_Go百科e2', 'setting3' => 10)
I was now going to use foreach to loop over the items and print them like this:
foreach($settings as $setting => $value) {
if (is_string($value)) { $value = "'" . $value . "'"; }
$output .= $setting . ':' . $value .',';
}
which should make me end up with:
(window).load(function() {
$('#widget').myWidget({
setting1:'value1',
setting2:'value2',
setting3:10})
With the current setup I end up with the last entry having a ',' at the end (one too many) which means I get a Javascript error, so I need to remove it.
All with all, I have the feeling I'm doing something very dirty (including the is_string check) and I was wondering if there is a neat way to deal with this?
There is a json_encode function if you're using PHP >= 5.2
You should use json_encode()
for this. It does all the dirty work for you.
(window).load(function() {
$('#widget').myWidget(
<?php echo json_encode($settings); ?>
);
}
Have you tried json_encode ?
Exemple from the docs:
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Would output
{"a":1,"b":2,"c":3,"d":4,"e":5}
Here's a little thing I like to use when dealing with situations like this. I know it doesn't really answer your question, but it is an elegant way of solving the comma problem.
$comma = '';
foreach($settings as $setting => $value) {
if (is_string($value)) {
$value = "'" . $value . "'";
$output .= $comma . $setting . ':' . $value;
$comma = ',';
}
}
So on the first run $comma is blank, but after that it gets put between every new entry.
精彩评论