douzhang1115 2017-11-08 17:15
浏览 71
已采纳

foreach循环中的迭代器

I have a site where we've loaded a hidden input and array with a value that was coming from a php function which we've now removed. Tha variable in question is rownum and the function was:

public function setskuRosNums()
{
$r = 1;
foreach($this->pgroups as &$pgroup){
    foreach($pgroup->pskus as &$psku){
        $psku->rownum = $r;
        $r++;
    }
}
}

Since the function has been removed, I want to basically add an iterator to my foreach loop to replace it. This was being used to loop through all of our products and associated an incremented row number to each sku.

I have a foreach loop in my laravel blade that loops the skus and I want to use an iterator to index each one that way as an efficient alternative to what that old function was doing.

Here's the current loop/code:

@foreach ($pgroup->pskus as $psku)
<?php $tempdata[$psku->rownum] = $psku ?>
    <tr>
    <td style="font-weight: 500; line-height: 30px; font-size: 14px;">{{ $psku->frame_fmt }}</td>
    <input type="hidden" name="rownum" value="{{$psku->rownum}}" />
    </td></tr>
@endforeach

So the $psku->rownum will change and I will have a new variable for the iterator to put in it's place. How can I do this and create an iterator in the foreach loop so that it associates a number to each sku?

  • 写回答

1条回答 默认 最新

  • drbi19093 2017-11-08 17:29
    关注

    Delete unneeded &s from your local variables in foreach loops:

    foreach($this->pgroups as &$pgroup){
        foreach($pgroup->pskus as &$psku){
            $psku->rownum = $r;
            $r++;
        }
    }
    

    Should be

    foreach($this->pgroups as $pgroup){ // & deleted
        foreach($pgroup->pskus as $psku){ // & deleted
            $psku->rownum = $r;
            $r++;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 Qt 不小心删除了自带的类,该怎么办
    • ¥15 我需要在PC端 开两个抖店工作台客户端.(语言-java)
    • ¥15 有没有哪位厉害的人可以用C#可视化呀
    • ¥15 可以帮我看看代码哪里错了吗
    • ¥15 设计一个成绩管理系统
    • ¥15 PCL注册的选点等函数如何取消注册
    • ¥15 问一下各位,为什么我用蓝牙直接发送模拟输入的数据,接收端显示乱码呢,米思齐软件上usb串口显示正常的字符串呢?
    • ¥15 Python爬虫程序
    • ¥15 crypto 这种的应该怎么找flag?
    • ¥15 代码已写好,求帮我指出错误,有偿!