简体   繁体   English

遍历PHP数组以使用PHP foreach创建Javascript数组

[英]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. 在制作PHP数组的PHP数组迭代期间,我在使用烦人的','时遇到了一些麻烦。 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? 注意JavaScript数组中的多余逗号吗? 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? 我将如何重新编写此PHP代码段,以免出现多余的逗号,从而产生格式正确的JavaScript数组?

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. 您不需要自己执行此操作,PHP有一个名为json_encode的函数json_encode您的需要。 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. 如果由于某种原因您没有PHP 5.2.0,则该页面的注释中有很多实现可以解决此问题。

Use implode() to glue up array elements. 使用implode()粘合数组元素。 It will take care about commas 会注意逗号

//later that page..in JavaScript

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

You can use this to generate the json array: 您可以使用它来生成json数组:

$list = json_encode($array);

And then read it in Javascript: 然后用Javascript阅读:

var list = <?=$list?>

How about converting array to a valid JSON object? 如何将数组转换为有效的JSON对象?

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

Anyway, do you really need to generate JS code on the fly? 无论如何,您真的需要即时生成JS代码吗? 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. JS生成通常被认为是一种hack,在许多情况下可以轻松避免。

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);
];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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