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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?