doudou0111 2017-01-16 22:50 采纳率: 0%
浏览 62
已采纳

使用FOR循环比较和增加字符串值

I'm trying to compare new string against old string from database, and if that string exists increase it by one, for example if string car exists new string should be car-1 and if that string exist then car-2...

I'm using Laravel, and have achieved that by using while() loop, but I would like to do it with for() loop too.

This is my code that works:

foreach($lang_codes as $key => $value)
{               
    $oldAlias = str_slug($request->{"new_category_lang_{$value->code}"}, '-');
    $newAlias = $oldAlias;
    $aliasCheck = ShopCategoryName::where('alias', $oldAlias)->first();
    $newCategory = new ShopCategoryName;

    $i = 1;
    while ($aliasCheck) 
    {
        $newAlias = $oldAlias . '-' . $i;
        $aliasCheck = ShopCategoryName::where('alias', $newAlias)->first();
        $i++;
    }
}

I was trying to use strcmp() with for() loop, but I don't know how to put that code together, it was mess.

So basically, I'm trying code above to work with for() loop, but my brain has blocked and overcomplicated.

  • 写回答

1条回答 默认 最新

  • duangewu5234 2017-01-16 23:37
    关注

    This part

    $i = 1;
    while ($aliasCheck) 
    {
        $newAlias = $oldAlias . '-' . $i;
        $aliasCheck = ShopCategoryName::where('alias', $newAlias)->first();
        $i++;
    }
    

    is equivalent to

    for ($i = 1; $aliasCheck; $i++) 
    {
        $newAlias = $oldAlias . '-' . $i;
        $aliasCheck = ShopCategoryName::where('alias', $newAlias)->first();
    }
    

    You can also rewrite your code to:

    $oldAlias = str_slug($request->{"new_category_lang_{$value->code}"}, '-');
    $newAlias = $oldAlias;
    $newCategory = new ShopCategoryName; // <-- not sure what that is good for
    
    for ($i = 1; ShopCategoryName::where('alias', $newAlias)->exists(); ++$i) 
    {
        $newAlias = $oldAlias . '-' . $i;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址