简体   繁体   中英

Iterating over PHP array to create Javascript array with PHP foreach

I'm having a bit of trouble with an annoying ',' during the iteration of a PHP array to produce a Javascript array. Essentially, what I have is this:

<?php
  $array = array(StdObject,StdObject,StdObject);
?>

//later that page...in JavaScript

var list = [
<?php foreach($array as $value):?>
  '<?=$value->some_letter_field?>',
<?endforeach;?>
];

Unfortunatly, what this code does is produce output that looks like this:

var list = ['a','b','c',];

Notice that extra comma in the JavaScript array? This is causing some issues. How would I go about re-writing this PHP snippet so that extra comma doesn't get printed, producing a properly formatted JavaScript array?

The expected output should be:

var list = ['a','b','c'];

I appreciate your help in advance.

You don't need to do this yourself, PHP has a function called json_encode that does what you want. If for some reason you don't have PHP 5.2.0, there are a lot of implementations in the comments of that page to get around that.

Use implode() to glue up array elements. It will take care about commas

//later that page..in JavaScript

var list = ['<?=implode("', '", $array)?>'];

You can use this to generate the json array:

$list = json_encode($array);

And then read it in Javascript:

var list = <?=$list?>

How about converting array to a valid JSON object?

var list = JSON.parse("<?php echo json_encode($array); ?>");

Anyway, do you really need to generate JS code on the fly? Isn't there another way to complete your task? JS generation is often considered a hack, and it can be avoided easily in many cases.

This will do the trick:

<?php 
$filtered = array();
foreach($array as $value) {
    $filtered[] = $value->some_letter_field;
}
echo 'var list = ' . json_encode($filtered);
?>

If you insist in keeping your current code for whatever reason, just:

var list = [
<?php foreach($array as $value): ?>
  $output[] = "'".$value->some_letter_field."'";
<?php endforeach; ?>
  echo implode(',', $output);
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM