Search code examples
exacttargetampscript

AMPSCRIPT - String building with a for loop


I want to print out the different names of friends that are in this database. Depending on the name chosen, it'll print out the list of friends associated with that name.

%%[

    FOR @y = 1 TO @friendRowcount DO 
        Set @friendRow = Row(@friendRows,@y)
        Set @friendName = Lookup("DB_FriendIDToName","friend_name","friendid",FIELD(@FriendRow,"friendid"),"language",Lowercase(@lookupLang))    

        Set @NameList = CONCAT(@NameList, @friendName, ", ")

    NEXT @y
    Set @bodytext = Replace(@bodytext,"PLACEHOLDERFRIENDNAMES", @NameList)


    Set @bodyText = "Your friends are PLACEHOLDERFRIENDNAMES."
]%%

%%=v(@bodyText)=%%

The problem is that it only prints out one name and not the comma separated list. Seeing how the list will usually be a different length then the others, I don't know how to do this dynamically.

The output I want to see is "Your friends are Name1, Name2, Name3, and Name4."

I am currently seeing "Your friends are Name3" because it is replacing @Name (and in turn @NameList) each time it looks instead of adding it.

edit: updated the code and it is a step in the right direction. The last issue I ran into was figuring out how to tackle the " and Name#" portion.


Solution

  • %%[
    
    Set @bodyText = "Your friends are PLACEHOLDERFRIENDNAMES."
    
    FOR @y = 1 TO @friendRowcount DO 
        Set @friendRow = Row(@friendRows,@y)
        Set @friendName = Lookup("DB_FriendIDToName","friend_name","friendid",FIELD(@FriendRow,"friendid"),"language",Lowercase(@lookupLang))    
    
        IF (@y == 1) THEN
            Set @NameList = @friendName
        ELSEIF (@y < @friendRowcount) THEN
            Set @NameList = CONCAT(@NameList,", ",@friendName)
        ELSEIF (@y == @friendRowcount) THEN
            Set @NameList = CONCAT(@NameList, ", and ", @friendName)
        ENDIF 
    
    NEXT @y
    Set @bodyText = Replace(@bodyText,"PLACEHOLDERFRIENDNAMES", @NameList)
    
    ]%%
    
    %%=v(@bodyText)=%%
    

    Fixed the middle section. Thanks for the help! Included the dreaded oxford comma for those situations that could arise and create confusion.