Javascript 中的 PHP foreach 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21708008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:30:48  来源:igfitidea点击:

PHP foreach loop in Javascript

javascriptphploopsforeach

提问by Krs

How can i make a loop like this one in Javascript?

如何在 Javascript 中创建这样的循环?

foreach ($viewData['cure'] as $cure) 

In this loop I would like to print the result in JS

在这个循环中,我想在 JS 中打印结果

$("#new").append('<label for="nice_text">ID Type</label><input type="text" id="nice_text" name="cureIdtype" class="input-text" VALUE="<?php echo (string)$cure["id_type"] ?>"/>');

回答by Skwal

You can simply combine both like this

您可以像这样简单地将两者结合起来

<script type="text/javascript">
<?php foreach ($viewData['cure'] as $cure): ?>
$("#new").append('<label for="nice_text<?php echo $cure["id"] ?>">ID Type</label><input type="text" id="nice_text<?php echo $cure["id"] ?>"/>" name="cureIdtype" class="input-text" value="<?php echo (string)$cure["id_type"] ?>"/>');
<?php endforeach; ?>
</script>

Just make sure your Ids are unique (I added $cure["id"]as an example), you might also wanna change the name="cureIdtype", depending on what you want to do with the input afterwards.

只需确保您的 Id 是唯一的(我$cure["id"]作为示例添加),您可能还想更改name="cureIdtype",具体取决于您之后要对输入做什么。

回答by Infineight

Was googling this for myself to see if there was something more elegant than what I have below and didn't see my solution mentioned.

自己在谷歌上搜索这个,看看是否有比我下面的更优雅的东西,但没有看到我的解决方案。

PHP

PHP

foreach ( $viewData['cure'] as $cure ) {
    ?>
    // your code from above
    $("#new").append('<label for="nice_text">ID Type</label><input type="text" id="nice_text" name="cureIdtype" class="input-text" value="<?php echo $cure["id_type"]; ?>"/>');
    <?php
}

Javascript

Javascript

var cures = <?php echo json_encode( $viewData['cure'] ); ?>;
for ( var key in cures ) {
    var cure = cures[key];
    // your code from above modified to use the Javascript variable created
    $("#new").append('<label for="nice_text">ID Type</label><input type="text" id="nice_text" name="cureIdtype" class="input-text" value="'+cure["id_type"]+'"/>');
}

回答by Viraj Mohite

Following is one of the way you can write or use forEach in Javascript.

以下是您可以在 Javascript 中编写或使用 forEach 的一种方式。

const arr = ['value0', 'value1', 'value2'];
arr.forEach(element => {
  console.log(element);
});

Also you can refer this linkwhich helps you to understand difference between for and forEach in javascript.

您也可以参考此链接,它可以帮助您了解 javascript 中 for 和 forEach 之间的区别。

const arr = ['value0', 'value1', 'value2'];
for (let i in arr) {  
  console.log(arr[i])
}

回答by Thom Wiggers

Javascript doesn't have foreachlike PHP, you need to use a regular forloop.

Javascriptforeach不像 PHP,你需要使用常规for循环。

var a = ["a", "b", "c"];
for (var index = 0; index < a.length; ++index) {
    console.log(a[index]);
}

(from https://stackoverflow.com/questions/9329446/for-each-in-an-array-how-to-do-that-in-javascript)

(来自https://stackoverflow.com/questions/9329446/for-each-in-an-array-how-to-do-that-in-javascript

回答by Nick Coons

If you want to do this in PHP and echo the content to the browser, it would look like this:

如果您想在 PHP 中执行此操作并将内容回显到浏览器,它将如下所示:

foreach ($viewData['cure'] as $cure) {
    echo '$("#new").append("<label for=\'nice_text\'>ID Type</label><input type=\'text\' id=\'nice_text\' name=\'cureIdtype\' class=\'input-text\' VALUE=\'' . (string)$cure['id_type'] . '\'/>")';
}

If you have a JavaScript array and want to handle this there, it would look something like this:

如果你有一个 JavaScript 数组并想在那里处理它,它看起来像这样:

for (var i = 0; i < viewData['cure'].length; ++i) {
    $("#new").append('<label for="nice_text">ID Type</label><input type="text" id="nice_text" name="cureIdtype" class="input-text" VALUE="' + viewData['cure'][i]['id_type'] + '"/>")';
}

These examples are untested, and littered with a variety of single/double quotes and escapes, so I could have made some typos in there.

这些示例未经测试,并且散布着各种单/双引号和转义符,因此我可能会在其中输入一些拼写错误。

回答by silentw

Javascript Array forEach() Method

Javascript 数组 forEach() 方法



Description:

描述:

Javascript array forEach()method calls a function for each element in the array.

Javascript 数组forEach()方法为数组中的每个元素调用一个函数。

Syntax:

句法:

array.forEach(callback[, thisObject]);

array.forEach(callback[, thisObject]);

Here is the detail of parameters:

下面是参数的详细信息:

  • callback :Function to test each element of the array.
  • thisObject :Object to use as this when executing callback.
  • callback :测试数组每个元素的函数。
  • thisObject :在执行回调时用作 this 的对象。

Return Value:

返回值:

Returns created array.

返回创建的数组。

Compatibility:

兼容性:

This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work you need to add following code at the top of your script:

该方法是 ECMA-262 标准的 JavaScript 扩展;因此,它可能不会出现在标准的其他实现中。要使其工作,您需要在脚本顶部添加以下代码:

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}

Example:

例子:

<html>
<head>
<title>JavaScript Array forEach Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}

function printBr(element, index, array) {
  document.write("<br />[" + index + "] is " + element ); 
}

[12, 5, 8, 130, 44].forEach(printBr);

</script>
</body>
</html>

This will produce following result:

这将产生以下结果:

[0] is 12
[1] is 5
[2] is 8
[3] is 130
[4] is 44 

To understand it in better way you can Try it yourself.

要更好地理解它,您可以自己尝试

SOURCE

SOURCE

回答by Netzach

var a = ["a", "b", "c", "d"];
a.forEach(function(data) {
    console.log(data);
});

I don't understand what is the problem with your code...

我不明白你的代码有什么问题......

<script>
var array = [];
<? foreach ($viewData['cure'] as $cure) {?>
    array.push(<? echo $cure?>);
<? }?>
array.forEach(function(value){
    $("#new").append('<label for="nice_text">ID Type</label><input type="text" id="nice_text" name="cureIdtype" class="input-text" VALUE="'+value+'"/>')
});

</script>