【问题标题】:PHP foreach loop in JavascriptJavascript中的PHP foreach循环
【发布时间】:2014-03-09 14:27:29
【问题描述】:

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

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

在这个循环中我想在 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"] ?>"/>');

【问题讨论】:

标签: javascript php loops foreach


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

    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

    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"]+'"/>');
    }
    

    【讨论】:

      【解决方案3】:
      var a = ["a", "b", "c", "d"];
      a.forEach(function(data) {
          console.log(data);
      });
      

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

      <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>
      

      【讨论】:

        【解决方案4】:

        Javascript 数组 forEach() 方法


        说明:

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

        语法:

        array.forEach(callback[, thisObject]);

        参数详情如下:

        • 回调:函数来测试数组的每个元素。
        • thisObject : 执行回调时用作 this 的对象。

        返回值:

        返回创建的数组。

        兼容性:

        此方法是对 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);
            }
          };
        }
        

        示例:

        <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>
        

        这将产生以下结果:

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

        要更好地理解它,您可以Try it yourself

        SOURCE

        【讨论】:

          【解决方案5】:

          如果您想在 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'] . '\'/>")';
          }
          

          如果你有一个 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'] + '"/>")';
          }
          

          这些示例未经测试,并且充斥着各种单引号/双引号和转义符,因此我可能会在其中打错字。

          【讨论】:

            【解决方案6】:

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

            <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>
            

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

            【讨论】:

              【解决方案7】:

              Javascript没有像PHP那样的foreach,你需要使用常规的for循环。

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

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

              【讨论】:

              猜你喜欢
              • 2011-06-11
              • 1970-01-01
              • 2016-09-26
              • 2012-07-19
              • 1970-01-01
              • 2018-05-02
              • 1970-01-01
              • 2017-05-28
              • 2015-12-10
              相关资源
              最近更新 更多