在一个foreach循环,我得到了一个静态id谁保持不变,但我希望它改变每次foreach循环张贴一个新的行


In a foreach loop i got a static id who stays the same but i want it to change everytime the foreach loop post a new line

foreach()循环中,我得到了一个保持不变的静态ID,但我希望它在每次foreach()循环发布新行时都改变。

我已经尝试了for()环和foreach()环,并且在下面的例子中,我使用一个数组,但我得到以下错误:

数组到字符串的转换

我想要的:

id="1",id="2",id="3",id="4",id="5";

我的代码:

private function recursiveTemplate($templates){

    foreach($templates as $key => $template){
        $templatenames =array(1,2,3,4,5);
        $int=0;
        if(is_array($template)){
            $this->templateHtml .= '<div class="input-group tempHolder"><span style="width: 155px;" class="input-group-addon" id='.$key.'>'.$key.'</span>';
            $this->recursiveTemplate($template);
            $this->templateHtml .= '
               <button type="button" class="btn2 btn-info"  id="addTemplate"><span class="glyphicon glyphicon-plus">
               <button type="button" class="btn2 btn-danger"  id="deleteTemplate" ><span class="glyphicon glyphicon-minus"></span></span></div>';
        }else{
            $this->templateHtml .= '<input type="text" class="form-control" id="'.$templatenames .'" name="jezus" aria-describedby="basic-addon3" value="'.$template.'">';
        }

    }
}

}

您必须向您的函数发送额外的参数。我在下面做了一个完整的工作示例:

<?php
class MyClass
{
    // public $templateHtml;
    // ...
    public function recursiveTemplate($templates, $counter = 0)
    {
        foreach ($templates as $key => $template) {
            if (is_array($template)) {
                $this->templateHtml .= '<div class="input-group tempHolder"><span style="width: 155px;" class="input-group-addon" id=' . $key . '>' . $key . '</span>';
                $this->recursiveTemplate($template, $counter++); // <-- Note the counter
                $this->templateHtml .= '
                   <button type="button" class="btn2 btn-info"  id="addTemplate"><span class="glyphicon glyphicon-plus">
                   <button type="button" class="btn2 btn-danger"  id="deleteTemplate" ><span class="glyphicon glyphicon-minus"></span></span></div>';
            } else {
                $this->templateHtml .= '<input type="text" class="form-control" id="' . ($counter += 1) . '" name="jezus" aria-describedby="basic-addon3" value="' . $template . '">';
            }
        }
    }
    // ...
    public function render()
    {
        $this->recursiveTemplate(['a', 'b', ['d', 'e']]);
        echo $this->templateHtml;
    }
}
$Obj = new MyClass();
$Obj->render();