Attribute
- CFML Reference User Guide
- ColdFusion functions
- ColdFusion functions by category
- Functions a-b
- Abs
- ACos
- AddSOAPRequestHeader
- AddSOAPResponseHeader
- AjaxLink
- AjaxOnLoad
- ApplicationStop
- ArrayAppend
- ArrayAvg
- ArrayClear
- ArrayContains
- ArrayContainsNoCase
- ArrayDelete
- ArrayDeleteAt
- ArrayDeleteNoCase
- ArrayEach
- ArrayFilter
- ArrayFind
- ArrayFindAll
- ArrayFindAllNoCase
- ArrayFindNoCase
- ArrayInsertAt
- ArrayIsDefined
- ArrayIsEmpty
- ArrayLen
- ArrayMap
- ArrayMax
- ArrayMin
- ArrayNew
- ArrayPrepend
- ArrayReduce
- ArrayResize
- ArraySet
- ArraySetMetadata
- ArraySlice
- ArraySort
- ArraySum
- ArraySwap
- ArrayToList
- Asc
- ASin
- Atn
- AuthenticatedContext
- AuthenticatedUser
- BinaryDecode
- BinaryEncode
- BitAnd
- BitMaskClear
- BitMaskRead
- BitMaskSet
- BitNot
- BitOr
- BitSHLN
- BitSHRN
- BitXor
- BooleanFormat
- Abs
- Functions-c-d
- CacheGet
- CacheGetAllIds
- CacheGetMetadata
- CacheGetProperties
- CacheGetSession
- CacheIdExists
- CachePut
- CacheRegionExists
- CacheRegionNew
- CacheRegionRemove
- CacheRemove
- CacheRemoveAll
- CacheSetProperties
- CallStackDump
- CallStackGet
- CanDeSerialize
- Canonicalize
- CanSerialize
- Ceiling
- CharsetDecode
- CharsetEncode
- Chr
- CJustify
- Compare
- CompareNoCase
- Cos
- CreateDate
- CreateDateTime
- CreateObject
- CreateObject: .NET object
- CreateObject: COM object
- CreateObject: component object
- CreateObject: CORBA object
- CreateObject: Java or EJB object
- CreateObject: web service object
- CreateODBCDate
- CreateODBCDateTime
- CreateODBCTime
- CreateSignedJWT
- CreateEncryptedJWT
- CreateTime
- CreateTimeSpan
- CreateUUID
- CSRFGenerateToken
- CSRFVerifyToken
- CSVRead
- CSVWrite
- CSVProcess
- DateAdd
- DateCompare
- DateConvert
- DateDiff
- DateFormat
- DatePart
- DateTimeFormat
- Day
- DayOfWeek
- DayOfWeekAsString
- DayOfYear
- DaysInMonth
- DaysInYear
- DE
- DecimalFormat
- DecodeForHTML
- DecodeFromURL
- DecrementValue
- Decrypt
- DecryptBinary
- DeleteClientVariable
- Deserialize
- DeserializeJSON
- DeserializeXML
- DirectoryCopy
- DirectoryCreate
- DirectoryDelete
- DirectoryExists
- DirectoryList
- DirectoryRename
- DollarFormat
- DotNetToCFType
- Duplicate
- Functions-e-g
- EncodeForCSS
- EncodeForDN
- EncodeForHTML
- EncodeForHTMLAttribute
- EncodeForJavaScript
- EncodeForLDAP
- EncodeForURL
- EncodeForXML
- EncodeForXMLAttribute
- EncodeForXpath
- Encrypt
- EncryptBinary
- EntityDelete
- EntityLoad
- EntityLoadByExample
- EntityLoadByPK
- EntityMerge
- EntityNew
- EntityReload
- EntitySave
- EntityToQuery
- Evaluate
- Exp
- ExpandPath
- FileClose
- FileCopy
- FileDelete
- FileExists
- FileGetMimeType
- FileIsEOF
- FileMove
- FileOpen
- FileRead
- FileReadBinary
- FileReadLine
- FileSeek
- FileSetAccessMode
- FileSetAttribute
- FileSetLastModified
- FileSkipBytes
- FileUpload
- FileUploadAll
- FileWrite
- FileWriteLine
- Find
- FindNoCase
- FindOneOf
- FirstDayOfMonth
- Fix
- Floor
- FormatBaseN
- GeneratePBKDFKey
- GenerateSecretKey
- GetApplicationMetadata
- GetAuthUser
- GetBaseTagData
- GetBaseTagList
- GetBaseTemplatePath
- GetClientVariablesList
- GetComponentMetaData
- GetContextRoot
- GetCPUUsage
- GetCurrentTemplatePath
- GetCSPNonce
- GetDirectoryFromPath
- GetEncoding
- GetException
- GetFileFromPath
- GetFileInfo
- GetFreeSpace
- GetFunctionCalledName
- GetFunctionList
- GetGatewayHelper
- GetHttpRequestData
- GetHttpTimeString
- GetK2ServerDocCount
- GetK2ServerDocCountLimit
- GetLocale
- GetLocaleDisplayName
- GetLocalHostIP
- GetMetaData
- GetMetricData
- GetPageContext
- GetPropertyString
- GetPropertyFile
- GetPrinterInfo
- GetPrinterList
- GetProfileSections
- GetProfileString
- GetReadableImageFormats
- GetSafeHTML
- GetSAMLAuthRequest
- GetSAMLLogoutRequest
- Generate3DesKey
- GenerateSAMLSPMetadata
- GetSOAPRequest
- GetSOAPRequestHeader
- GetSOAPResponse
- GetSOAPResponseHeader
- GetSystemFreeMemory
- GetSystemTotalMemory
- GetTempDirectory
- GetTempFile
- GetTemplatePath
- GetTickCount
- GetTimeZoneInfo
- GetToken
- GetTotalSpace
- GetUserRoles
- GetVFSMetaData
- GetWriteableImageFormats
- Functions-h-im
- Hash
- HMac
- Hour
- HQLMethods
- HTMLCodeFormat
- HTMLEditFormat
- IIf
- ImageAddBorder
- ImageBlur
- ImageClearRect
- ImageCopy
- ImageCreateCaptcha
- ImageCrop
- ImageDrawArc
- ImageDrawBeveledRect
- ImageDrawCubicCurve
- ImageDrawLine
- ImageDrawLines
- ImageDrawOval
- ImageDrawPoint
- ImageDrawQuadraticCurve
- ImageDrawRect
- ImageDrawRoundRect
- ImageDrawText
- ImageFlip
- ImageGetBlob
- ImageGetBufferedImage
- ImageGetEXIFMetadata
- ImageGetEXIFTag
- ImageGetHeight
- ImageGetIPTCMetadata
- ImageGetIPTCTag
- ImageGetMetadata
- ImageGetWidth
- ImageGrayscale
- ImageInfo
- ImageMakeColorTransparent
- ImageMakeTranslucent
- ImageNegative
- ImageNew
- ImageOverlay
- ImagePaste
- ImageRead
- ImageReadBase64
- ImageResize
- ImageRotate
- ImageRotateDrawingAxis
- ImageScaleToFit
- ImageSetAntialiasing
- ImageSetBackgroundColor
- ImageSetDrawingColor
- ImageSetDrawingStroke
- ImageSetDrawingTransparency
- ImageSharpen
- ImageShear
- ImageShearDrawingAxis
- ImageTranslate
- ImageTranslateDrawingAxis
- ImageWrite
- ImageWriteBase64
- ImageXORDrawingMode
- Functions-in-k
- IncrementValue
- InputBaseN
- Insert
- Int
- InterruptThread
- InvalidateOauthAccesstoken
- Invoke
- InitSAMLAuthRequest
- InitSAMLLogoutRequest
- InvokeCFClientFunction
- IsArray
- IsAuthenticated
- IsAuthorized
- IsBinary
- IsBoolean
- IsClosure
- IsCustomFunction
- IsDate
- IsDateObject
- IsDDX
- IsDebugMode
- IsDefined
- IsImage
- IsImageFile
- IsInstanceOf
- IsIPv6
- IsJSON
- IsK2ServerABroker
- IsK2ServerDocCountExceeded
- IsK2ServerOnline
- IsLeapYear
- IsLocalHost
- IsNull
- IsNumeric
- IsNumericDate
- IsObject
- isOnline
- IsPDFArchive
- IsPDFFile
- IsPDFObject
- IsProtected
- IsQuery
- isSamlLogoutResponse
- isSafeHTML
- IsSimpleValue
- IsSOAPRequest
- IsSpreadsheetFile
- IsSpreadsheetObject
- IsStruct
- isThreadInterrupted
- IsUserInAnyRole
- IsUserInRole
- IsUserLoggedIn
- IsValid
- IsValidOauthAccesstoken
- IsWDDX
- IsXML
- IsXmlAttribute
- IsXmlDoc
- IsXmlElem
- IsXmlNode
- IsXmlRoot
- JavaCast
- JSStringFormat
- Functions-l
- LCase
- Left
- Len
- ListAppend
- ListChangeDelims
- ListContains
- ListContainsNoCase
- ListDeleteAt
- ListEach
- ListFilter
- ListFind
- ListFindNoCase
- ListFirst
- ListGetAt
- ListGetDuplicates
- ListInsertAt
- ListLast
- ListLen
- ListMap
- ListPrepend
- ListQualify
- ListReduce
- ListRemoveDuplicates
- ListRest
- ListSetAt
- ListSort
- ListToArray
- ListValueCount
- ListValueCountNoCase
- LJustify
- Location
- Log
- Log10
- LSCurrencyFormat
- LSDateFormat
- LSDateTimeFormat
- LSEuroCurrencyFormat
- LSIsCurrency
- LSIsDate
- LSIsNumeric
- LSNumberFormat
- LSParseCurrency
- LSParseDateTime
- LSParseEuroCurrency
- LSParseNumber
- LSTimeFormat
- LTrim
- Functions-m-r
- Max
- Mid
- Min
- Minute
- Month
- MonthAsString
- Now
- NumberFormat
- ObjectEquals
- ObjectLoad
- ObjectSave
- OnWSAuthenticate
- ORMClearSession
- ORMCloseAllSessions
- ORMCloseSession
- ORMEvictCollection
- ORMEvictEntity
- ORMEvictQueries
- ORMExecuteQuery
- ORMFlush
- ORMFlushall
- ORMGetSession
- ORMGetSessionFactory
- ORMIndex
- ORMIndexPurge
- ORMReload
- ORMSearch
- ORMSearchOffline
- ParagraphFormat
- ParameterExists
- ParseDateTime
- Pi
- PrecisionEvaluate
- ProcessSAMLResponse
- ProcessSAMLLogoutRequest
- Quarter
- PreserveSingleQuotes
- QueryAddColumn
- QueryAddRow
- QueryConvertForGrid
- QueryExecute
- QueryFilter
- QueryGetResult
- QueryGetRow
- QueryKeyExists
- QueryMap
- QueryNew
- QueryReduce
- QuerySetCell
- QuotedValueList
- QueryEach
- Rand
- Randomize
- RandRange
- ReEscape
- REFind
- REFindNoCase
- ReleaseComObject
- REMatch
- REMatchNoCase
- RemoveCachedQuery
- RemoveChars
- RepeatString
- Replace
- ReplaceList
- ReplaceNoCase
- REReplace
- REReplaceNoCase
- RestDeleteApplication
- RestSetResponse
- RestInitApplication
- Reverse
- Right
- RJustify
- Round
- RTrim
- Functions-s
- Second
- SendGatewayMessage
- SendSAMLLogoutResponse
- Serialize
- SerializeJSON
- SerializeXML
- SessionInvalidate
- SessionRotate
- SessionGetMetaData
- SessionInvalidate
- SessionRotate
- SetDay
- SetEncoding
- SetHour
- SetLocale
- SetMonth
- SetProfileString
- SetPropertyString
- SetVariable
- SetYear
- Sgn
- Sin
- Sleep
- SpanExcluding
- SpanIncluding
- SpreadsheetAddAutoFilter
- SpreadsheetAddColumn
- SpreadsheetAddFreezePane
- SpreadsheetAddImage
- SpreadsheetAddInfo
- SpreadsheetAddPageBreaks
- SpreadsheetAddRow
- SpreadsheetAddRows
- SpreadsheetAddSplitPane
- SpreadsheetCreateSheet
- SpreadsheetDeleteColumn
- SpreadsheetDeleteColumns
- SpreadsheetDeleteRow
- SpreadsheetDeleteRows
- SpreadsheetFormatCell
- SpreadsheetFormatColumn
- SpreadsheetFormatCellRange
- SpreadsheetFormatColumn
- SpreadsheetFormatColumns
- SpreadsheetFormatRow
- SpreadsheetFormatRows
- SpreadsheetGetCellComment
- SpreadsheetGetCellFormula
- SpreadsheetGetCellValue
- SpreadsheetGetColumnCount
- SpreadsheetInfo
- SpreadsheetMergeCells
- SpreadsheetNew
- SpreadsheetRead
- SpreadsheetReadBinary
- SpreadsheetRemoveSheet
- SpreadsheetSetActiveSheet
- SpreadsheetSetActiveSheetNumber
- SpreadsheetSetCellComment
- SpreadsheetSetCellFormula
- SpreadsheetSetCellValue
- SpreadsheetSetColumnWidth
- SpreadsheetSetFooter
- SpreadsheetSetHeader
- SpreadsheetSetRowHeight
- SpreadsheetShiftColumns
- SpreadsheetShiftRows
- SpreadsheetWrite
- StreamingSpreadsheetNew
- StreamingSpreadsheetCleanup
- StreamingSpreadsheetRead
- StreamingSpreadsheetProcess
- SpreadsheetSetFooterImage
- SpreadsheetSetHeaderImage
- SpreadsheetSetFittoPage
- SpreadsheetUngroupColumns
- SpreadsheetGroupColumns
- SpreadsheetUngroupRows
- SpreadsheetGroupRows
- SpreadsheetRemoveColumnBreak
- SpreadsheetSetColumnBreak
- SpreadsheetRemoveRowBreak
- SpreadsheetSetRowBreak
- SpreadsheetRemovePrintGridlines
- SpreadsheetAddPrintGridlines
- SpreadsheetGetColumnWidth
- SpreadsheetSetColumnHidden
- SpreadsheetSetRowHidden
- SpreadsheetisColumnHidden
- SpreadsheetisRowHidden
- SpreadsheetisStreamingXmlFormat
- SpreadsheetisXmlFormat
- SpreadsheetisBinaryFormat
- SpreadsheetRenameSheet
- SpreadsheetRemoveSheetNumber
- SpreadsheetGetLastRowNumber
- SpreadsheetGetPrintOrientation
- Sqr
- StripCR
- StructAppend
- StructClear
- StructCopy
- StructCount
- StructDelete
- StructEach
- StructFilter
- StructFind
- StructFindKey
- StructFindValue
- StructGet
- StructGetMetadata
- StructInsert
- StructIsEmpty
- StructKeyArray
- StructKeyExists
- StructKeyList
- StructMap
- StructNew
- StructReduce
- StructSetMetadata
- StructSort
- StructToSorted
- StructUpdate
- StructValueArray
- StoreSetMetadata
- StoreGetACL
- StoreGetMetadata
- StoreAddACL
- StoreSetACL
- Functions-t-z
- Tan
- ThreadJoin
- ThreadTerminate
- Throw
- TimeFormat
- ToBase64
- ToBinary
- ToScript
- ToString
- Trace
- Transactionandconcurrency
- TransactionCommit
- TransactionRollback
- TransactionSetSavePoint
- Trim
- UCase
- URLDecode
- URLEncodedFormat
- URLSessionFormat
- Val
- ValueList
- VerifyClient
- Week
- Wrap
- WriteDump
- WriteLog
- WriteOutput
- WSGetAllChannels
- WSGetSubscribers
- WSPublish
- WSSendMessage
- XmlChildPos
- XmlElemNew
- XmlFormat
- XmlGetNodeType
- XmlNew
- XmlParse
- XmlSearch
- XmlTransform
- XmlValidate
- Year
- YesNoFormat
- ColdFusion tags
- ColdFusion tag summary
- ColdFusion tags by category
- Application framework tags
- Communications tags
- Database manipulation tags
- Data output tags
- Debugging tags
- Exception handling tags
- Extensibility tags
- File management tags
- Flow-control tags
- Forms tags
- Internet Protocol tags
- Page processing tags
- Security tags
- Variable manipulation tags
- Other tags
- Tags a-b
- Tags c
- cfcache
- cfcalendar
- cfcase
- cfcatch
- cfchart
- cfchart tag in ColdFusion
- Get started with cfchart
- Customize a chart using cfchart
- Advanced cfchart customization options
- Create an area chart in ColdFusion
- Create line charts in ColdFusion
- Create bar charts in ColdFusion
- Create floating bar charts in ColdFusion
- Create histograms in ColdFusion
- Create pie charts in ColdFusion
- Create funnel charts in ColdFusion
- Create pyramid charts in ColdFusion
- Create curve charts in ColdFusion
- Create boxplots in ColdFusion
- Create donut charts in ColdFusion
- Create bubble charts in ColdFusion
- Create scatterplots in ColdFusion
- Create radar charts in ColdFusion
- Other chart types in ColdFusion (Cone, Cylinder, Piano, and Bullet)
- Advanced customization options in cfchart
- cfchartdata
- cfchartseries
- cfchartset
- cfclient
- cfclientsettings
- cfcol
- cfcollection
- cfcomponent
- cfcontent
- cfcontinue
- cfcookie
- Tags f
- cffeed
- cffile
- cffile action = "append"
- cffile action = "copy"
- cffile action = "delete"
- cffile action = "move"
- cffile action = "read"
- cffile action = "readBinary"
- cffile action = "rename"
- cffile action = "upload"
- cffile action = "uploadAll"
- cffile action = "write"
- cffileupload
- cffinally
- cfflush
- cfform
- cfformgroup
- cfformitem
- cfftp
- cfftp: Connection: file and directory operations
- cfftp: Opening and closing FTP server connections
- cfftp : Opening and closing secure FTP server connections
- cfftp action = "listDir"
- cffunction
- Tags g-h
- Tags i
- Tags j-l
- cfjava
- cflayout
- cflayoutarea
- cfldap
- cflocation
- cflock
- cflog
- cflogin
- cfloginuser
- cflogout
- cfloop
- cfloop : conditional loop
- cfloop : index loop
- cfloop : looping over a COM collection or structure
- cfloop : looping over a date or time range
- cfloop : looping over a list, a file, or an array
- cfloop : looping over a query
- Tags m-o
- cfmail
- cfmailparam
- cfmailpart
- cfmap
- cfmapitem
- cfmediaplayer
- cfmenu
- cfmenuitem
- cfmessagebox
- cfmodule
- cfNTauthenticate
- cfoauth
- cfobject
- cfobject: .NET object
- cfobject: COM object
- cfobject: component object
- cfobject: CORBA object
- cfobject: Java or EJB object
- cfobject: web service object
- cfobjectcache
- cfoutput
- Tags p-q
- Tags r-s
- Tags t
- Tags u-z
- CFML Reference
- Reserved words and variables
- Ajax JavaScript functions
- Ajax JavaScript functions
- Function summary Ajax
- ColdFusion.Ajax.submitForm
- ColdFusion.Autosuggest.getAutosuggestObject
- ColdFusion.Layout.enableSourceBind
- ColdFusion.MessageBox.getMessageBoxObject
- ColdFusion.ProgressBar.getProgressBarObject
- ColdFusion.MessageBox.isMessageBoxDefined
- JavaScriptFunctionsinColdFusion9Update1
- ColdFusion ActionScript functions
- ColdFusion mobile functions
- Application.cfc reference
- Script functions implemented as CFCs
- ColdFusion Flash Form style reference
- Styles valid for all controls
- Styles for cfform
- Styles for cfformgroup with horizontal or vertical type attributes
- Styles for box-style cfformgroup elements
- Styles for cfformgroup with accordion type attribute
- Styles for cfformgroup with tabnavigator type attribute
- Styles for cfformitem with hrule or vrule type attributes
- Styles for cfinput with radio, checkbox, button, image, or submit type attributes
- Styles for cftextarea tag and cfinput with text, password, or hidden type attributes
- Styles for cfselect with size attribute value of 1
- Styles for cfselect with size attribute value greater than 1
- Styles for cfcalendar tag and cfinput with dateField type attribute
- Styles for the cfgrid tag
- Styles for the cftree tag
- ColdFusion Flash Form Style Reference
- ColdFusion event gateway reference
- ColdFusion Event Gateway reference
- addEvent
- CFEvent
- CFEventclass
- Constructor
- Gateway development interfaces and classes
- getStatus
- setCFCPath
- setCFCMethod
- getOriginatorID
- getLogger
- getBuddyList
- getBuddyInfo
- IM gateway message sending commands
- IM Gateway GatewayHelper class methods
- onIncomingMessage
- onIMServerMessage
- onBuddyStatus
- onAddBuddyResponse
- onAddBuddyRequest
- IM Gateway CFC incoming message methods
- IM gateway methods and commands
- CFML CFEvent structure
- warn
- info
- setOriginatorID
- data command
- submit Multi command
- submit command
- setGatewayType
- setGatewayID
- setData
- setCFCListeners
- outgoingMessage
- getStatusTimeStamp
- numberOfMessagesReceived
- numberOfMessagesSent
- removeBuddy
- removeDeny
- removePermit
- setNickName
- setPermitMode
- setStatus
- SMS Gateway CFEvent structure and commands
- SMS Gateway incoming message CFEvent structure
- getStatusAsString
- getProtocolName
- getPermitMode
- getPermitList
- getNickName
- getName
- getDenyList
- getCustomAwayMessage
- getQueueSize
- getMaxQueueSize
- getHelper
- getGatewayType
- getGatewayServices
- getGatewayID_1
- getGatewayID
- getData
- getCFCTimeout
- setCFCTimeout
- getCFCPath
- getCFCMethod
- GatewayServices class
- Gateway interface
- GatewayHelper interface
- addPermit
- addDeny
- addBuddy
- error
- debug
- Logger class
- stop
- start
- CFML event gateway SendGatewayMessage data parameter
- restart
- fatal
- SMS gateway message sending commands
- ColdFusion C++ CFX Reference
- ColdFusion Java CFX reference
- WDDX JavaScript Objects
- Cloud services
- ColdFusion and GCP Storage
- ColdFusion and GCP Firestore
- ColdFusion and GCP PubSub
- ColdFusion and Amazon S3
- ColdFusion and DynamoDB
- ColdFusion and Amazon SQS
- ColdFusion and Amazon SNS
- ColdFusion and MongoDB
- ColdFusion and Azure Blob
- ColdFusion and Azure Service Bus
- Multi-cloud storage services
- Multi-cloud RDS databases
- ColdFusion and Azure Cosmos DB
Description
Looping over a list steps through elements contained in any of these entities:
- A variable
- A value that is returned from an expression
- An array
- A file Looping over a file does not open the entire file in memory.
Syntax
<cfloop index = "index name" item = "item name" array = "array" characters = "number of characters" delimiters = "item delimiter" file = "absolute path and filename" charset = "a charset to use when reading the file" list = "list items" ... </cfloop>
See also
History
ColdFusion (2018 release) Update 2: The script variant of cfloop supports iterating over an array, list, and struct.
ColdFusion 8: Added the characters, file, and array attributes.
cfloop - Array
|
|
Required/Optional |
Description |
|
array |
Required |
The array object. |
|
index |
Optional. In earlier versions of ColdFusion, this attribute was required. In ColdFusion (2016 release), this attribute is optional. Either item or index is required. |
The current value of the array. |
|
item |
Optional |
The current element of the array. In ColdFusion (2016 release), you need to use either item or index; or use both the attributes together. |
The following code sample throws an exception, since neither item nor index was used:
<cfset myArray = ["John", "Paul", "George", "Ringo"] > <cfloop array="#myArray#"> <cfoutput>#x# <br/> </cfoutput> </cfloop>
Use the attribute index as shown below:
<cfset myArray = ["John", "Paul", "George", "Ringo"] > <cfloop array="#myArray#" index="idx"> <cfoutput>#idx# <br/> </cfoutput> </cfloop>
Output
John Paul George Ringo
Use the attribute item, as shown below:
<cfset myArray = ["John", "Paul", "George", "Ringo"] > <cfloop array="#myArray#" item="itm"> <cfoutput>#itm# <br/> </cfoutput> </cfloop>
Output
John Paul George Ringo
Use both item and index attributes together, as shown below:
<cfset myArray = ["John", "Paul", "George", "Ringo"] > <cfloop array="#myArray#" item="Beatles" index="name"> <cfoutput>#name# : #Beatles# <br/> </cfoutput> </cfloop>
Output
1 : John 2 : Paul 3 : George 4 : Ringo
Looping over multi-dimensional arrays
A multi-dimensional array is an array of arrays rather than an array of single values.
To read an element from a two-dimensional array, you must first identify the index of the row and then identify the index of the column. For example, the song "Surfer Girl" is in row 3, column 1, so it is identified as aBeachBoysAlbums[3][1].
To loop through a two-dimensional array, you must nest one loop inside of another.
<cfset aBeachBoysAlbums = ArrayNew(2)> <!---Build first album array, Surfin' Safari---> <cfset aBeachBoysAlbums[1][1] = "Surfin' Safari"> <cfset aBeachBoysAlbums[1][2] = "County Fair"> <cfset aBeachBoysAlbums[1][3] = "Ten Little Indians"> <!---Build second album array, Surfin' USA---> <cfset aBeachBoysAlbums[2][1] = "Surfin' USA"> <cfset aBeachBoysAlbums[2][2] = "Farmer's Daughter"> <cfset aBeachBoysAlbums[2][3] = "Miserlou"> <!---Build third album array, Surfer Girl---> <cfset aBeachBoysAlbums[3][1] = "Surfer Girl"> <cfset aBeachBoysAlbums[3][2] = "Catch a Wave"> <cfset aBeachBoysAlbums[3][3] = "The Surfer Moon"> <!---<cfdump var="#aBeachBoysAlbums#" >---> <!--- loop ---> <cfloop from="1" to="#ArrayLen(aBeachBoysAlbums)#" index="i"> <cfoutput> <cfloop from="1" to="#ArrayLen(aBeachBoysAlbums[i])#" index="j"> Album: #i# Song #j#: #aBeachBoysAlbums[i][j]#</br> </cfloop> </cfoutput> </cfloop>
Output
Album: 1 Song 1: Surfin' Safari
Album: 1 Song 2: County Fair
Album: 1 Song 3: Ten Little Indians
Album: 2 Song 1: Surfin' USA
Album: 2 Song 2: Farmer's Daughter
Album: 2 Song 3: Miserlou
Album: 3 Song 1: Surfer Girl
Album: 3 Song 2: Catch a Wave
Album: 3 Song 3: The Surfer Moon
Alternatively, you can use an array of structures and loop through the array to extract the key-value pairs.
For example,
<cfscript>
data = [
{code:"USA", count:324459463},
{code:"UK", count:66181585},
{code:"CAN", count:36624199},
{code:"FRA", count:64979548},
{code:"NED", count:17035938},
{code:"GER", count:82114224}
];
</cfscript>
<cfloop array="#data#" index="i">
<cfoutput>
The population of #i.code#: #i.count#<br>
</cfoutput>
</cfloop>
Output
The population of USA: 324459463
The population of UK: 66181585
The population of CAN: 36624199
The population of FRA: 64979548
The population of NED: 17035938
The population of GER: 82114224
cfloop as script
<cfscript>
myArray = ["John", "Paul", "George", "Ringo"];
cfloop(array=myArray, index="idx"){
writeOutput(#idx# & "<br/>");
}
</cfscript>
Output
John
Paul
George
Ringo
cfloop - List
|
Attribute |
Required/Optional |
Description |
|
list |
Required |
List of elements. |
|
index |
Optional |
The current value of the list. |
|
item |
Optional |
The current element of the list. In ColdFusion (2016 release), you need to use either item or index; or use both the attributes together. |
|
Delimiters |
Optional |
Characters that separate list items. |
The following code sample throws an exception, since neither item nor index was used:
<cfset myList="John,Paul|George|Ringo"/> <cfloop list="#myList#" delimiters=",|"> <cfoutput> #name# </cfoutput> </cfloop>
Use the attribute index as shown below. The sample below does not use delimiters attribute.
<cfset myList="John,Paul,George,Ringo"/> <!---Loop through the list with attribute index ---> <cfloop list="#myList#" index="name"> <cfoutput> #name# </cfoutput> </cfloop>
Output
John Paul George Ringo
Use the attribute item as shown below. The sample below does not use delimiters attribute.
<cfset myList="John,Paul,George,Ringo"/> <!---Loop through the list with attribute item ---> <cfloop list="#myList#" item="Beatles"> <cfoutput> #Beatles# </cfoutput> </cfloop>
Output
John Paul George Ringo
You can use both item and index together, as shown below:
<cfset beatles="John,Paul,George,Ringo"/> <!---Loop through the list with attributes item and index ---> <cfloop list="#beatles#" item="name" index="i"> <cfoutput> #i#:#name# </cfoutput> </cfloop>
Using delimiters in cfloop - list
Delimiters are characters that separate list items. For example,
- Item1, item2, item3, item4 (comma-separated list)
- Item1, item2 | item3 | item4 (comma and pipe-separated list)
In the code samples below:
<cfset myList="John,Paul|George|Ringo"/> <!---Loop through the list with attributes index and delimiters ---> <cfloop list="#myList#" index="name" delimiters="|"> <cfoutput> #name# </cfoutput> </cfloop>
Output
John, Paul George Ringo
<cfset myList="John,Paul|George|Ringo"/> <!---Loop through the list with attributes index and delimiters ---> <cfloop list="#myList#" index="name" delimiters=",|"> <cfoutput> #name# </cfoutput> </cfloop>
Output
John Paul George Ringo
cfloop as script
<cfscript>
myList="1,2,3,4"
cfloop(list=myList, index="i", item="j") {
writeOutput("index:" & i)
writeOutput("item:" & j & "")
}
</cfscript>
Output
index:1item:1
index:2item:2
index:3item:3
index:4item:4
cfloop - File
|
Attribute |
Required/Optional |
Description |
|
file |
Required |
The file attribute denotes the absolute path and filename of the text file to read, one line at a time. When reading large text files, you can reuse the value of the index variable, which contains the current line of the file. When the loop completes, ColdFusion closes the file. |
|
item |
Optional |
Values are line or chars (In ColdFusion 2016). Denotes how the file is read. |
|
index |
Optional |
In ColdFusion (2016 release), you need to use either item or index; or use both the attributes together. |
|
character |
Optional |
The attribute denotes the number of characters to read during each iteration of the loop from the file specified in the file attribute. If the value of the characters attribute is more than the number of characters in the file, ColdFusion uses the number of characters in the file. |
|
charset |
Optional |
Character set to use when reading the file. |
In the code sample below, ColdFusion opens the text file, myfile.txt, reads each character, and displays the first 20 characters (including spaces) during each iteration of the loop.
<cfset myFile="c:\out\myfile.txt"/>
<cfloop file="#myFile#" index="i" item="chars" characters="20">
<cfoutput>
#i#:#chars#<br />
</cfoutput>
</cfloop>
The next sample reads each line of the file, using the index and item attributes.
<cfset myFile="c:\out\myfile.txt"/>
<cfloop file="#myFile#" index="i" item="line">
<cfoutput>
#i#:#line#<br />
</cfoutput>
</cfloop>
cfloop - Struct
When looping in a struct, each item in the struct is referenced by the variable name in the item attribute. The loop executes until all items have been accessed.
|
Attribute |
Required/Optional |
Description |
|
collection |
Required |
A struct object. |
|
item |
Required |
The structure key that is used to iterate through the key-value pairs. The collection attribute is used with the item attribute. |
For example, in the sample below, the item key iterates through each struct item and displays the key-value pair.
<cfscript>
Team = {"Marketing" = "John", "Sales" : {"Executive" : "Tom", "Assistant" = "Mike"},"IT":{"Developers":{"Dev1":"Ashley","Dev2"="Jason"}}};
</cfscript>
<cfloop collection="#Team#" item="key" >
<cfoutput>#Key#:</cfoutput>
<cfdump var="#Team[key]#">
<br/>
</cfloop>
cfloop as script
<cfscript>
Team = {"Marketing" = "John", "Sales" : {"Executive" : "Tom", "Assistant" = "Mike"},"IT":{"Developers":{"Dev1":"Ashley","Dev2"="Jason"}}};
cfloop(collection=Team ,item="key"){
writeOutput(#Key# & ":");
writeOutput(#SerializeJSon(Team[key])#);
writeOutput("<br/>");
}
</cfscript>
Output
Marketing:"John"
IT:{"Developers":{"Dev2":"Jason","Dev1":"Ashley"}}
Sales:{"Executive":"Tom","Assistant":"Mike"}
Real-world uses of the cfloop tag
E-Commerce order processing and fulfillment
Online retailers struggle with complex order processing where each order contains multiple items requiring individual inventory validation, shipping calculations, and fulfillment routing across different warehouses. Manual processing is error-prone and can't scale during peak shopping periods. Implement automated order processing system that systematically validates inventory, calculates shipping costs based on item attributes and destinations, and routes orders to appropriate fulfillment centers based on stock availability and proximity.
`<cfloop array="#order.items#">` iterates through all order items for validation and calculations. `<cfloop collection="#orderData#">` processes nested customer and shipping data. `<cfloop list="#shippingZones#">` handles shipping zones efficiently.
<cfscript>
// Sample customer orders with multiple items
customerOrders = [
{
"orderId": "ORD-2024-001",
"customerId": 12345,
"items": [
{"productId": "ELEC001", "name": "Laptop Pro 15", "category": "Electronics", "quantity": 1, "price": 1299.99, "weight": 4.5},
{"productId": "ACC002", "name": "Wireless Mouse", "category": "Accessories", "quantity": 2, "price": 49.99, "weight": 0.2},
{"productId": "ACC003", "name": "USB-C Cable", "category": "Accessories", "quantity": 3, "price": 19.99, "weight": 0.1}
],
"shippingZone": "West",
"priority": "Standard"
},
{
"orderId": "ORD-2024-002",
"customerId": 67890,
"items": [
{"productId": "ELEC004", "name": "Tablet 10 inch", "category": "Electronics", "quantity": 2, "price": 599.99, "weight": 1.2},
{"productId": "ACC005", "name": "Screen Protector", "category": "Accessories", "quantity": 4, "price": 12.99, "weight": 0.05}
],
"shippingZone": "East",
"priority": "Express"
}
];
// Inventory levels by product
inventory = {
"ELEC001": 15,
"ACC002": 50,
"ACC003": 100,
"ELEC004": 8,
"ACC005": 200
};
// Shipping zones and rates
shippingZones = "West,East,North,South,Central";
shippingRates = {
"West": {"Standard": 8.99, "Express": 19.99},
"East": {"Standard": 9.99, "Express": 21.99},
"North": {"Standard": 7.99, "Express": 18.99},
"South": {"Standard": 8.49, "Express": 19.49},
"Central": {"Standard": 6.99, "Express": 16.99}
};
</cfscript>
<cfoutput>
<h2>📦 Order Processing Dashboard</h2>
<div style="background: ##f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop Array Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop array="##customerOrders##" index="order"><br>
<cfloop array="##order.items##" index="item"><br>
<!--- Process each order item ---><br>
</cfloop><br>
</cfloop>
</div>
<cfset totalOrderValue = 0>
<cfset totalItems = 0>
<cfset inventoryIssues = 0>
<cfloop array="#customerOrders#" index="order">
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##28a745; margin: 15px 0;">
<h4 style="margin-top: 0; color: ##28a745;">Order #order.orderId# - Customer #order.customerId#</h4>
<cfset orderSubtotal = 0>
<cfset orderWeight = 0>
<cfset orderItemCount = 0>
<table style="width: 100%; border-collapse: collapse; margin: 10px 0;">
<thead>
<tr style="background: ##e8f5e8;">
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Product</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: center;">Qty</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: right;">Price</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: right;">Total</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: center;">Stock</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: center;">Status</th>
</tr>
</thead>
<tbody>
<cfloop array="#order.items#" index="item">
<cfset itemTotal = item.quantity * item.price>
<cfset orderSubtotal += itemTotal>
<cfset orderWeight += (item.quantity * item.weight)>
<cfset orderItemCount += item.quantity>
<cfset totalItems += item.quantity>
<cfset stockAvailable = inventory[item.productId]>
<cfset stockStatus = (stockAvailable GTE item.quantity) ? "✅ Available" : "❌ Insufficient">
<cfif stockAvailable LT item.quantity>
<cfset inventoryIssues += 1>
</cfif>
<tr>
<td style="padding: 8px; border: 1px solid ##ddd;">
<strong>#item.name#</strong><br>
<small style="color: ##666;">ID: #item.productId# | #item.category#</small>
</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: center;">#item.quantity#</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: right;">$#NumberFormat(item.price, "0.00")#</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: right;">$#NumberFormat(itemTotal, "0.00")#</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: center;">#stockAvailable#</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: center;">#stockStatus#</td>
</tr>
</cfloop>
</tbody>
</table>
<cfset totalOrderValue += orderSubtotal>
<cfset shippingCost = shippingRates[order.shippingZone][order.priority]>
<cfset orderTotal = orderSubtotal + shippingCost>
<div style="background: ##f8f9fa; padding: 10px; border-radius: 3px; margin-top: 10px;">
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px;">
<div style="text-align: center;">
<strong>#orderItemCount#</strong><br>
<small>Items</small>
</div>
<div style="text-align: center;">
<strong>#NumberFormat(orderWeight, "0.0")# lbs</strong><br>
<small>Weight</small>
</div>
<div style="text-align: center;">
<strong>$#NumberFormat(orderSubtotal, "0.00")#</strong><br>
<small>Subtotal</small>
</div>
<div style="text-align: center;">
<strong>$#NumberFormat(shippingCost, "0.00")#</strong><br>
<small>#order.shippingZone# #order.priority#</small>
</div>
<div style="text-align: center;">
<strong>$#NumberFormat(orderTotal, "0.00")#</strong><br>
<small>Total</small>
</div>
</div>
</div>
</div>
</cfloop>
<h3>📊 Processing Summary:</h3>
<div style="background: ##d4edda; padding: 15px; border-radius: 5px;">
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
<div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
<h3 style="margin: 0; color: ##28a745;">#ArrayLen(customerOrders)#</h3>
<p style="margin: 5px 0 0 0;">Orders Processed</p>
</div>
<div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
<h3 style="margin: 0; color: ##17a2b8;">#totalItems#</h3>
<p style="margin: 5px 0 0 0;">Total Items</p>
</div>
<div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
<h3 style="margin: 0; color: ##fd7e14;">$#NumberFormat(totalOrderValue, "0,000.00")#</h3>
<p style="margin: 5px 0 0 0;">Order Value</p>
</div>
<div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
<h3 style="margin: 0; color: #(inventoryIssues GT 0) ? "##dc3545" : "##28a745"#;">#inventoryIssues#</h3>
<p style="margin: 5px 0 0 0;">Inventory Issues</p>
</div>
</div>
</div>
</div>
<h2>🚚 Shipping Zone Analysis</h2>
<div style="background: ##fff3cd; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop List Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop list="##shippingZones##" index="zone"><br>
<!--- Process each shipping zone ---><br>
</cfloop>
</div>
<h3>📍 Available Shipping Zones:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##fd7e14;">
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 15px 0;">
<cfloop list="#shippingZones#" index="zone">
<div style="background: ##fff8e1; padding: 15px; border-radius: 5px; text-align: center;">
<h4 style="margin: 0 0 10px 0; color: ##fd7e14;">#zone# Region</h4>
<div style="background: white; padding: 8px; border-radius: 3px; margin: 5px 0;">
<strong>Standard:</strong> $#NumberFormat(shippingRates[zone]["Standard"], "0.00")#
</div>
<div style="background: white; padding: 8px; border-radius: 3px; margin: 5px 0;">
<strong>Express:</strong> $#NumberFormat(shippingRates[zone]["Express"], "0.00")#
</div>
</div>
</cfloop>
</div>
</div>
</div>
<h2>📋 Inventory Status Check</h2>
<div style="background: ##f8d7da; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop Struct Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop collection="##inventory##" item="productId"><br>
<!--- Check inventory levels ---><br>
</cfloop>
</div>
<h3>📦 Current Inventory Levels:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##dc3545;">
<table style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="background: ##f8d7da;">
<th style="padding: 10px; border: 1px solid ##ddd; text-align: left;">Product ID</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: center;">Stock Level</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: center;">Status</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: center;">Reorder Alert</th>
</tr>
</thead>
<tbody>
<cfloop collection="#inventory#" item="productId">
<cfset stockLevel = inventory[productId]>
<cfset stockStatus = "">
<cfset reorderAlert = "">
<cfif stockLevel GTE 50>
<cfset stockStatus = "🟢 High">
<cfelseif stockLevel GTE 20>
<cfset stockStatus = "🟡 Medium">
<cfelseif stockLevel GTE 10>
<cfset stockStatus = "🟠 Low">
<cfelse>
<cfset stockStatus = "🔴 Critical">
</cfif>
<cfif stockLevel LT 15>
<cfset reorderAlert = "⚠️ Reorder Now">
<cfelse>
<cfset reorderAlert = "✅ OK">
</cfif>
<tr>
<td style="padding: 10px; border: 1px solid ##ddd; font-family: monospace;">#productId#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center; font-weight: bold;">#stockLevel#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">#stockStatus#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">#reorderAlert#</td>
</tr>
</cfloop>
</tbody>
</table>
</div>
</div>
</cfoutput>
Employee directory and HR management systems
HR departments manage complex employee data across multiple departments, locations, and organizational hierarchies. Generating reports, processing payroll, and maintaining compliance requires navigating nested data structures and processing varying organizational changes. Build detailed HR system that dynamically processes organizational hierarchies, generates regulatory-compliant reports, and handles employee lifecycle events through systematic data processing and standardized report generation.
`<cfloop collection="#departments#">` navigates complex employee hierarchies by department and role. `<cfloop query="employeeData">` iterates through database records for report generation. Nested loops process multi-level organizational structures (company > department > team > employee). Handles varying data structures as organizations evolve.
<cfscript>
// Company organizational structure
companyStructure = {
"Executive": {
"CEO": {"id": 1001, "name": "Sarah Johnson", "salary": 250000, "hireDate": "2020-01-15", "email": "sarah.johnson@company.com"},
"CTO": {"id": 1002, "name": "Michael Chen", "salary": 220000, "hireDate": "2020-03-22", "email": "michael.chen@company.com"},
"CFO": {"id": 1003, "name": "Lisa Rodriguez", "salary": 210000, "hireDate": "2020-05-10", "email": "lisa.rodriguez@company.com"}
},
"Engineering": {
"Director": {"id": 2001, "name": "David Wilson", "salary": 160000, "hireDate": "2021-02-15", "email": "david.wilson@company.com"},
"Senior Developers": [
{"id": 2101, "name": "Alice Brown", "salary": 125000, "hireDate": "2021-06-01", "email": "alice.brown@company.com", "skills": "Java,Python,AWS"},
{"id": 2102, "name": "Bob Davis", "salary": 130000, "hireDate": "2021-08-15", "email": "bob.davis@company.com", "skills": "React,Node.js,Docker"},
{"id": 2103, "name": "Carol Martinez", "salary": 128000, "hireDate": "2022-01-10", "email": "carol.martinez@company.com", "skills": "Python,ML,TensorFlow"}
],
"Developers": [
{"id": 2201, "name": "Tom Anderson", "salary": 95000, "hireDate": "2022-03-20", "email": "tom.anderson@company.com", "skills": "JavaScript,React,CSS"},
{"id": 2202, "name": "Jane Wilson", "salary": 92000, "hireDate": "2022-07-12", "email": "jane.wilson@company.com", "skills": "Java,Spring,MySQL"},
{"id": 2203, "name": "Mike Johnson", "salary": 88000, "hireDate": "2023-01-08", "email": "mike.johnson@company.com", "skills": "C##,.NET,Azure"}
]
},
"Sales": {
"VP Sales": {"id": 3001, "name": "Jennifer Taylor", "salary": 140000, "hireDate": "2021-04-05", "email": "jennifer.taylor@company.com"},
"Account Managers": [
{"id": 3101, "name": "Robert Garcia", "salary": 75000, "hireDate": "2022-02-14", "email": "robert.garcia@company.com", "territory": "West Coast"},
{"id": 3102, "name": "Amanda Clark", "salary": 78000, "hireDate": "2022-05-22", "email": "amanda.clark@company.com", "territory": "East Coast"},
{"id": 3103, "name": "Chris Lewis", "salary": 72000, "hireDate": "2023-03-15", "email": "chris.lewis@company.com", "territory": "Central"}
]
},
"Marketing": {
"Marketing Director": {"id": 4001, "name": "Emily White", "salary": 110000, "hireDate": "2021-09-30", "email": "emily.white@company.com"},
"Marketing Specialists": [
{"id": 4101, "name": "Daniel Kim", "salary": 65000, "hireDate": "2022-11-01", "email": "daniel.kim@company.com", "focus": "Digital Marketing"},
{"id": 4102, "name": "Jessica Moore", "salary": 62000, "hireDate": "2023-02-28", "email": "jessica.moore@company.com", "focus": "Content Strategy"}
]
}
};
// Department budget allocations
departmentBudgets = {
"Executive": 680000,
"Engineering": 1200000,
"Sales": 375000,
"Marketing": 240000
};
// Performance ratings data
performanceRatings = QueryNew("employeeId,quarter,rating,goals", "integer,varchar,decimal,varchar");
QueryAddRow(performanceRatings, [
{employeeId: 2101, quarter: "Q3-2024", rating: 4.5, goals: "Complete mobile app,Lead junior developers"},
{employeeId: 2102, quarter: "Q3-2024", rating: 4.8, goals: "Frontend architecture,Code reviews"},
{employeeId: 2201, quarter: "Q3-2024", rating: 4.2, goals: "Component library,Testing framework"},
{employeeId: 3101, quarter: "Q3-2024", rating: 4.0, goals: "Q4 sales target,Client retention"},
{employeeId: 3102, quarter: "Q3-2024", rating: 4.6, goals: "New client acquisition,Team training"}
]);
// Skills inventory for technical roles
skillsInventory = "Java,Python,JavaScript,React,Node.js,AWS,Docker,C##,.NET,Azure,Machine Learning,TensorFlow,Spring,MySQL,CSS";
</cfscript>
<cfoutput>
<h2>🏢 Organizational Structure Overview</h2>
<div style="background: ##f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop Struct Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop collection="##companyStructure##" item="department"><br>
<cfloop collection="##companyStructure[department]##" item="role"><br>
<!--- Process each employee role ---><br>
</cfloop><br>
</cfloop>
</div>
<cfset companyTotalSalary = 0>
<cfset companyTotalEmployees = 0>
<cfset departmentCount = 0>
<cfloop collection="#companyStructure#" item="department">
<cfset departmentCount += 1>
<cfset deptData = companyStructure[department]>
<cfset deptEmployees = 0>
<cfset deptSalaryTotal = 0>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##17a2b8; margin: 15px 0;">
<h4 style="margin-top: 0; color: ##17a2b8;">📂 #department# Department</h4>
<div style="background: ##f8f9fa; padding: 10px; border-radius: 3px; margin: 10px 0;">
<strong>Budget Allocation:</strong> $#NumberFormat(departmentBudgets[department], "0,000")#
</div>
<cfloop collection="#deptData#" item="role">
<div style="background: ##e8f4f8; padding: 12px; border-radius: 3px; margin: 8px 0;">
<h5 style="margin: 0 0 8px 0; color: ##495057;">👔 #role#</h5>
<cfif IsStruct(deptData[role])>
<!--- Individual employee (like Director, VP) --->
<cfset employee = deptData[role]>
<cfset deptEmployees += 1>
<cfset deptSalaryTotal += employee.salary>
<div style="background: white; padding: 8px; border-radius: 3px;">
<strong>#employee.name#</strong> (ID: #employee.id#)<br>
<small>📧 #employee.email# | 💰 $#NumberFormat(employee.salary, "0,000")# | 📅 Hired: #DateFormat(employee.hireDate, "mm/dd/yyyy")#</small>
</div>
<cfelseif IsArray(deptData[role])>
<!--- Team members array --->
<cfloop array="#deptData[role]#" index="employee">
<cfset deptEmployees += 1>
<cfset deptSalaryTotal += employee.salary>
<div style="background: white; padding: 8px; border-radius: 3px; margin: 5px 0;">
<strong>#employee.name#</strong> (ID: #employee.id#)<br>
<small>📧 #employee.email# | 💰 $#NumberFormat(employee.salary, "0,000")# | 📅 Hired: #DateFormat(employee.hireDate, "mm/dd/yyyy")#</small>
<cfif StructKeyExists(employee, "skills")>
<br><span style="color: ##28a745;">🔧 Skills: #employee.skills#</span>
</cfif>
<cfif StructKeyExists(employee, "territory")>
<br><span style="color: ##fd7e14;">🌍 Territory: #employee.territory#</span>
</cfif>
<cfif StructKeyExists(employee, "focus")>
<br><span style="color: ##dc3545;">🎯 Focus: #employee.focus#</span>
</cfif>
</div>
</cfloop>
</cfif>
</div>
</cfloop>
<div style="background: ##d1ecf1; padding: 10px; border-radius: 3px; margin-top: 10px;">
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 10px; text-align: center;">
<div>
<strong>#deptEmployees#</strong><br>
<small>Employees</small>
</div>
<div>
<strong>$#NumberFormat(deptSalaryTotal, "0,000")#</strong><br>
<small>Salary Total</small>
</div>
<div>
<strong>$#NumberFormat(deptSalaryTotal/deptEmployees, "0,000")#</strong><br>
<small>Avg Salary</small>
</div>
<div>
<strong>#NumberFormat((deptSalaryTotal/departmentBudgets[department])*100, "0.0")#%</strong><br>
<small>Budget Used</small>
</div>
</div>
</div>
</div>
<cfset companyTotalEmployees += deptEmployees>
<cfset companyTotalSalary += deptSalaryTotal>
</cfloop>
<h3>🎯 Company-Wide Summary:</h3>
<div style="background: ##d4edda; padding: 15px; border-radius: 5px;">
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
<div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
<h3 style="margin: 0; color: ##28a745;">#departmentCount#</h3>
<p style="margin: 5px 0 0 0;">Departments</p>
</div>
<div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
<h3 style="margin: 0; color: ##28a745;">#companyTotalEmployees#</h3>
<p style="margin: 5px 0 0 0;">Total Employees</p>
</div>
<div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
<h3 style="margin: 0; color: ##28a745;">$#NumberFormat(companyTotalSalary, "0,000,000")#</h3>
<p style="margin: 5px 0 0 0;">Total Payroll</p>
</div>
<div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
<h3 style="margin: 0; color: ##28a745;">$#NumberFormat(companyTotalSalary/companyTotalEmployees, "0,000")#</h3>
<p style="margin: 5px 0 0 0;">Average Salary</p>
</div>
</div>
</div>
</div>
<h2>📊 Performance Analytics Dashboard</h2>
<div style="background: ##fff3cd; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop Query Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop query="performanceRatings"><br>
<!--- Process performance data ---><br>
</cfloop>
</div>
<h3>⭐ Employee Performance Report:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##fd7e14;">
<table style="width: 100%; border-collapse: collapse; margin: 10px 0;">
<thead>
<tr style="background: ##fff3cd;">
<th style="padding: 10px; border: 1px solid ##ddd; text-align: left;">Employee ID</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: center;">Quarter</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: center;">Rating</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: left;">Goals</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: center;">Performance Level</th>
</tr>
</thead>
<tbody>
<cfset totalRating = 0>
<cfset ratingCount = 0>
<cfloop query="performanceRatings">
<cfset totalRating += rating>
<cfset ratingCount += 1>
<cfset performanceLevel = "">
<cfif rating GTE 4.5>
<cfset performanceLevel = "🌟 Excellent">
<cfelseif rating GTE 4.0>
<cfset performanceLevel = "✅ Good">
<cfelseif rating GTE 3.5>
<cfset performanceLevel = "⚡ Satisfactory">
<cfelse>
<cfset performanceLevel = "📈 Needs Improvement">
</cfif>
<tr>
<td style="padding: 10px; border: 1px solid ##ddd; font-family: monospace;">#employeeId#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">#quarter#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center; font-weight: bold;">#NumberFormat(rating, "0.0")#</td>
<td style="padding: 10px; border: 1px solid ##ddd;">
<cfloop list="#goals#" index="goal">
<span style="display: inline-block; background: ##f8f9fa; padding: 2px 6px; margin: 1px; border-radius: 3px; font-size: 0.85em;">#goal#</span>
</cfloop>
</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">#performanceLevel#</td>
</tr>
</cfloop>
</tbody>
</table>
<div style="background: ##fff8e1; padding: 12px; border-radius: 3px; text-align: center; margin-top: 15px;">
<strong>Average Performance Rating: #NumberFormat(totalRating/ratingCount, "0.00")# / 5.0</strong>
</div>
</div>
</div>
<h2>🔧 Skills Inventory Analysis</h2>
<div style="background: ##f8d7da; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop List Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop list="##skillsInventory##" index="skill"><br>
<!--- Analyze skill distribution ---><br>
</cfloop>
</div>
<h3>💻 Technical Skills Distribution:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##dc3545;">
<div style="background: ##f8f9fa; padding: 10px; border-radius: 3px; margin: 10px 0;">
<strong>Available Skills:</strong> #ListLen(skillsInventory)# different technologies
</div>
<cfset skillCategories = {}>
<cfset skillCounts = {}>
<cfloop list="#skillsInventory#" index="skill">
<!--- Categorize skills --->
<cfset category = "">
<cfif ListFindNoCase("Java,Python,JavaScript,C##", skill)>
<cfset category = "Programming Languages">
<cfelseif ListFindNoCase("React,Node.js,.NET,Spring", skill)>
<cfset category = "Frameworks">
<cfelseif ListFindNoCase("AWS,Azure,Docker", skill)>
<cfset category = "Cloud & DevOps">
<cfelseif ListFindNoCase("MySQL,TensorFlow", skill)>
<cfset category = "Databases & ML">
<cfelse>
<cfset category = "Web Technologies">
</cfif>
<cfif NOT StructKeyExists(skillCategories, category)>
<cfset skillCategories[category] = "">
</cfif>
<cfset skillCategories[category] = ListAppend(skillCategories[category], skill)>
<!--- Count skill occurrences (simulated based on employee data) --->
<cfset skillCount = RandRange(1, 8)>
<cfset skillCounts[skill] = skillCount>
</cfloop>
<cfloop collection="#skillCategories#" item="category">
<div style="background: ##f8f9fa; padding: 12px; border-radius: 3px; margin: 10px 0;">
<h5 style="margin: 0 0 8px 0; color: ##495057;">📚 #category#</h5>
<cfloop list="#skillCategories[category]#" index="skill">
<span style="display: inline-block; background: white; padding: 6px 10px; margin: 3px; border-radius: 5px; border: 1px solid ##ddd;">
<strong>#skill#</strong>
<span style="background: ##dc3545; color: white; padding: 2px 6px; border-radius: 10px; font-size: 0.8em; margin-left: 5px;">
#skillCounts[skill]# emp
</span>
</span>
</cfloop>
</div>
</cfloop>
<div style="background: ##f1f3f4; padding: 12px; border-radius: 3px; margin-top: 15px;">
<h5 style="margin: 0 0 8px 0;">🎯 Skills Summary:</h5>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px;">
<cfloop collection="#skillCategories#" item="category">
<div style="text-align: center; background: white; padding: 8px; border-radius: 3px;">
<strong>#ListLen(skillCategories[category])#</strong><br>
<small>#category#</small>
</div>
</cfloop>
</div>
</div>
</div>
</div>
</cfoutput>
File operations and data integration
nterprise systems need daily integration with external partners through file-based data exchange. Processing multi-gigabyte files (CSV, XML, EDI, logs) requires memory-efficient handling, format conversion, data validation, and error recovery without losing data integrity. Develop robust file processing system that handles large datasets line-by-line, validates each record during processing, supports multiple file formats, and continues processing even when encountering invalid records.
`<cfloop file="#filePath#">` reads large files line-by-line without memory constraints. `<cfloop file="#file#" characters="20">` handles fixed-width formats efficiently. Built-in delimiter support processes CSV and log files seamlessly. Continues processing after encountering invalid records while maintaining data quality.
<cfscript>
// Create sample CSV data for demonstration
customerDataCSV = "CustomerID,CompanyName,ContactName,Country,Phone,Email" & Chr(10) &
"1001,Acme Corp,John Smith,USA,555-0101,john.smith@acme.com" & Chr(10) &
"1002,Global Tech,Sarah Johnson,Canada,555-0102,sarah.j@globaltech.ca" & Chr(10) &
"1003,Euro Solutions,Hans Mueller,Germany,555-0103,h.mueller@eurosol.de" & Chr(10) &
"1004,Pacific Imports,Yuki Tanaka,Japan,555-0104,y.tanaka@pacific.jp" & Chr(10) &
"1005,Aussie Trading,Mike Wilson,Australia,555-0105,m.wilson@aussie.com.au" & Chr(10) &
"1006,Nordic Systems,Lars Andersen,Norway,555-0106,l.andersen@nordic.no" & Chr(10) &
"1007,Latin Commerce,Maria Garcia,Mexico,555-0107,m.garcia@latincom.mx";
// Sample log file content
serverLogData = "2024-10-29 08:15:23 [INFO] User login successful - UserID: 1001" & Chr(10) &
"2024-10-29 08:16:45 [INFO] Order created - OrderID: ORD-5678, Total: $299.99" & Chr(10) &
"2024-10-29 08:17:12 [ERROR] Database connection timeout - Service: CustomerDB" & Chr(10) &
"2024-10-29 08:18:33 [INFO] Payment processed - TransactionID: TXN-9876" & Chr(10) &
"2024-10-29 08:19:55 [WARNING] High memory usage detected - 85% utilized" & Chr(10) &
"2024-10-29 08:21:07 [ERROR] API rate limit exceeded - Service: PaymentGateway" & Chr(10) &
"2024-10-29 08:22:18 [INFO] User logout - UserID: 1001, Session: 45 minutes";
// Fixed-width file format specification
fixedWidthSpec = [
{"field": "RecordType", "start": 1, "length": 2},
{"field": "CustomerID", "start": 3, "length": 8},
{"field": "ProductCode", "start": 11, "length": 10},
{"field": "Quantity", "start": 21, "length": 5},
{"field": "UnitPrice", "start": 26, "length": 8},
{"field": "TransactionDate", "start": 34, "length": 10}
];
// Sample fixed-width data
fixedWidthData = "01000010013LAPTOP001 00002 129999 2024-10-29" & Chr(10) &
"01000010023MOUSE0012 00003 002999 2024-10-29" & Chr(10) &
"01000010034TABLET001 00001 059999 2024-10-29" & Chr(10) &
"01000020015CABLE0001 00005 001999 2024-10-29" & Chr(10) &
"01000020026KEYBOARD01 00001 007999 2024-10-29";
// File processing statistics
fileStats = {
"totalFiles": 0,
"totalRecords": 0,
"successfulRecords": 0,
"errorRecords": 0,
"processingTime": "0.0"
};
</cfscript>
<cfoutput>
<h2>📋 CSV File Processing</h2>
<div style="background: ##f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop File Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop list="##fileContent##" index="line" delimiters="#Chr(10)#"><br>
<!--- Process each line ---><br>
</cfloop>
</div>
<h3>🗂️ Customer Data Import Processing:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##28a745;">
<h4 style="margin-top: 0; color: ##28a745;">CSV Import: Customer Database Update</h4>
<cfset csvLines = ListToArray(customerDataCSV, Chr(10))>
<cfset headerProcessed = false>
<cfset recordCount = 0>
<cfset successCount = 0>
<cfset errorCount = 0>
<cfset csvHeaders = "">
<div style="background: ##f8f9fa; padding: 10px; border-radius: 3px; margin: 10px 0;">
<strong>Processing #ArrayLen(csvLines)# lines from customer data file...</strong>
</div>
<table style="width: 100%; border-collapse: collapse; margin: 10px 0;">
<thead>
<tr style="background: ##e8f5e8;">
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Line ##</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Customer ID</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Company</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Contact</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Country</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: center;">Status</th>
</tr>
</thead>
<tbody>
<cfset currentRow = 0>
<cfloop array="#csvLines#" index="line">
<cfset currentRow = currentRow + 1>
<cfif NOT headerProcessed AND currentRow EQ 1>
<cfset csvHeaders = line>
<cfset headerProcessed = true>
<tr style="background: ##fff3cd;">
<td colspan="6" style="padding: 8px; border: 1px solid ##ddd; text-align: center;">
<strong>📋 Headers:</strong> #csvHeaders#
</td>
</tr>
<cfelse>
<cfset recordCount += 1>
<cfset fields = ListToArray(line, ",")>
<!--- Validate record --->
<cfset isValid = (ArrayLen(fields) EQ 6 AND Len(Trim(fields[1])) GT 0)>
<cfif isValid>
<cfset successCount += 1>
<cfset statusIcon = "✅ Valid">
<cfset rowStyle = "background: white;">
<cfelse>
<cfset errorCount += 1>
<cfset statusIcon = "❌ Invalid">
<cfset rowStyle = "background: ##f8d7da;">
</cfif>
<tr style="#rowStyle#">
<td style="padding: 8px; border: 1px solid ##ddd;">#currentRow#</td>
<td style="padding: 8px; border: 1px solid ##ddd; font-family: monospace;">
#ArrayLen(fields) GTE 1 ? fields[1] : "N/A"#
</td>
<td style="padding: 8px; border: 1px solid ##ddd;">
#ArrayLen(fields) GTE 2 ? fields[2] : "N/A"#
</td>
<td style="padding: 8px; border: 1px solid ##ddd;">
#ArrayLen(fields) GTE 3 ? fields[3] : "N/A"#
</td>
<td style="padding: 8px; border: 1px solid ##ddd;">
#ArrayLen(fields) GTE 4 ? fields[4] : "N/A"#
</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: center;">#statusIcon#</td>
</tr>
</cfif>
</cfloop>
</tbody>
</table>
<div style="background: ##d4edda; padding: 10px; border-radius: 3px;">
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 10px; text-align: center;">
<div>
<strong>#recordCount#</strong><br>
<small>Records</small>
</div>
<div>
<strong>#successCount#</strong><br>
<small>Valid</small>
</div>
<div>
<strong>#errorCount#</strong><br>
<small>Errors</small>
</div>
<div>
<strong>#NumberFormat((successCount/recordCount)*100, "0.0")#%</strong><br>
<small>Success Rate</small>
</div>
</div>
</div>
</div>
</div>
<h2>📊 Log File Analysis</h2>
<div style="background: ##fff3cd; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop Line Processing Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop list="##logContent##" index="logLine" delimiters="#Chr(10)#"><br>
<!--- Parse log entry ---><br>
</cfloop>
</div>
<h3>🔍 Server Log Analysis Dashboard:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##fd7e14;">
<h4 style="margin-top: 0; color: ##fd7e14;">Real-time Log Processing & Alert Generation</h4>
<cfset logLines = ListToArray(serverLogData, Chr(10))>
<cfset infoCount = 0>
<cfset warningCount = 0>
<cfset errorCount = 0>
<cfset criticalEvents = ArrayNew(1)>
<table style="width: 100%; border-collapse: collapse; margin: 10px 0;">
<thead>
<tr style="background: ##fff3cd;">
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Timestamp</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: center;">Level</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Message</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: center;">Action</th>
</tr>
</thead>
<tbody>
<cfloop array="#logLines#" index="logLine">
<cfset logParts = ListToArray(logLine, " ", true)>
<cfset timestamp = "">
<cfset logLevel = "">
<cfset message = "">
<cfset alertLevel = "">
<cfset rowStyle = "">
<cfif ArrayLen(logParts) GTE 4>
<cfset timestamp = logParts[1] & " " & logParts[2]>
<cfset logLevel = Replace(Replace(logParts[3], "[", ""), "]", "")>
<cfset message = "">
<cfloop from="4" to="#ArrayLen(logParts)#" index="i">
<cfset message = message & " " & logParts[i]>
</cfloop>
<cfset message = Trim(message)>
<!--- Categorize and count log levels --->
<cfswitch expression="#logLevel#">
<cfcase value="INFO">
<cfset infoCount += 1>
<cfset alertLevel = "ℹ️ Info">
<cfset rowStyle = "background: ##d1ecf1;">
</cfcase>
<cfcase value="WARNING">
<cfset warningCount += 1>
<cfset alertLevel = "⚠️ Warning">
<cfset rowStyle = "background: ##fff3cd;">
<cfset ArrayAppend(criticalEvents, logLine)>
</cfcase>
<cfcase value="ERROR">
<cfset errorCount += 1>
<cfset alertLevel = "🚨 Error">
<cfset rowStyle = "background: ##f8d7da;">
<cfset ArrayAppend(criticalEvents, logLine)>
</cfcase>
<cfdefaultcase>
<cfset alertLevel = "📋 " & logLevel>
<cfset rowStyle = "background: white;">
</cfdefaultcase>
</cfswitch>
</cfif>
<tr style="#rowStyle#">
<td style="padding: 8px; border: 1px solid ##ddd; font-family: monospace; font-size: 0.85em;">#timestamp#</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: center;">#alertLevel#</td>
<td style="padding: 8px; border: 1px solid ##ddd; font-size: 0.9em;">#message#</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: center;">
<cfif logLevel EQ "ERROR">
<span style="background: ##dc3545; color: white; padding: 2px 6px; border-radius: 3px; font-size: 0.8em;">Alert</span>
<cfelseif logLevel EQ "WARNING">
<span style="background: ##fd7e14; color: white; padding: 2px 6px; border-radius: 3px; font-size: 0.8em;">Monitor</span>
<cfelse>
<span style="background: ##28a745; color: white; padding: 2px 6px; border-radius: 3px; font-size: 0.8em;">OK</span>
</cfif>
</td>
</tr>
</cfloop>
</tbody>
</table>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 15px;">
<div style="background: ##f8f9fa; padding: 12px; border-radius: 3px;">
<h5 style="margin: 0 0 8px 0;">📈 Log Level Summary</h5>
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; text-align: center;">
<div style="background: ##d1ecf1; padding: 8px; border-radius: 3px;">
<strong>#infoCount#</strong><br>
<small>Info</small>
</div>
<div style="background: ##fff3cd; padding: 8px; border-radius: 3px;">
<strong>#warningCount#</strong><br>
<small>Warnings</small>
</div>
<div style="background: ##f8d7da; padding: 8px; border-radius: 3px;">
<strong>#errorCount#</strong><br>
<small>Errors</small>
</div>
</div>
</div>
<div style="background: ##f8f9fa; padding: 12px; border-radius: 3px;">
<h5 style="margin: 0 0 8px 0;">🚨 Critical Events (#ArrayLen(criticalEvents)#)</h5>
<cfloop array="#criticalEvents#" index="event">
<div style="background: ##fff; padding: 4px 8px; margin: 2px 0; border-radius: 3px; border-left: 3px solid ##dc3545; font-size: 0.85em;">
#Left(event, 50)#<cfif Len(event) GT 50>...</cfif>
</div>
</cfloop>
</div>
</div>
</div>
</div>
<h2>📏 Fixed-Width File Processing</h2>
<div style="background: ##f8d7da; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop Character Processing Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop list="##fixedWidthData##" index="line" delimiters="#Chr(10)#"><br>
<!--- Extract fixed positions ---><br>
</cfloop>
</div>
<h3>💾 Legacy System Data Integration:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##dc3545;">
<h4 style="margin-top: 0; color: ##dc3545;">Fixed-Width Format: Mainframe Data Exchange</h4>
<div style="background: ##f8f9fa; padding: 10px; border-radius: 3px; margin: 10px 0;">
<strong>Field Specification:</strong>
<cfloop array="#fixedWidthSpec#" index="fieldSpec">
<span style="display: inline-block; background: white; padding: 3px 6px; margin: 2px; border-radius: 3px; font-size: 0.85em;">
#fieldSpec.field# (pos #fieldSpec.start#-#fieldSpec.start + fieldSpec.length - 1#)
</span>
</cfloop>
</div>
<cfset fixedLines = ListToArray(fixedWidthData, Chr(10))>
<cfset totalAmount = 0>
<table style="width: 100%; border-collapse: collapse; margin: 10px 0;">
<thead>
<tr style="background: ##f8d7da;">
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Record Type</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Customer ID</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Product Code</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: center;">Quantity</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: right;">Unit Price</th>
<th style="padding: 8px; border: 1px solid ##ddd; text-align: left;">Date</th>
</tr>
</thead>
<tbody>
<cfloop array="#fixedLines#" index="dataLine">
<cfset parsedData = {}>
<!--- Extract fields based on fixed positions --->
<cfloop array="#fixedWidthSpec#" index="fieldSpec">
<cfset fieldValue = Mid(dataLine, fieldSpec.start, fieldSpec.length)>
<cfset parsedData[fieldSpec.field] = Trim(fieldValue)>
</cfloop>
<cfset unitPrice = Val(parsedData.UnitPrice) / 100> <!--- Convert cents to dollars --->
<cfset lineTotal = Val(parsedData.Quantity) * unitPrice>
<cfset totalAmount += lineTotal>
<tr>
<td style="padding: 8px; border: 1px solid ##ddd; font-family: monospace;">#parsedData.RecordType#</td>
<td style="padding: 8px; border: 1px solid ##ddd; font-family: monospace;">#parsedData.CustomerID#</td>
<td style="padding: 8px; border: 1px solid ##ddd; font-family: monospace;">#parsedData.ProductCode#</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: center;">#Val(parsedData.Quantity)#</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: right;">$#NumberFormat(unitPrice, "0.00")#</td>
<td style="padding: 8px; border: 1px solid ##ddd;">#parsedData.TransactionDate#</td>
</tr>
</cfloop>
</tbody>
<tfoot>
<tr style="background: ##f5c6cb; font-weight: bold;">
<td colspan="5" style="padding: 8px; border: 1px solid ##ddd; text-align: right;">Total Transaction Value:</td>
<td style="padding: 8px; border: 1px solid ##ddd; text-align: right;">$#NumberFormat(totalAmount, "0,000.00")#</td>
</tr>
</tfoot>
</table>
</div>
</div>
</cfoutput>
Sales analytics and business intelligence
Sales organizations need real-time dashboards showing performance metrics across multiple dimensions (regions, products, time periods, representatives). Processing large transaction datasets for KPIs, trend analysis, and forecasting requires complex aggregations and multi-dimensional analysis. Create detailed analytics system that processes transaction data in real-time, calculates performance metrics across multiple dimensions, and generates dynamic reports with comparative analysis and predictive insights.
`<cfloop query="salesData">` iterates through large transaction datasets for real-time metric calculations. Nested loops enable cross-tabulation and drill-down analysis across multiple dimensions. Generates dynamic reports with varying structures based on user selections.
<cfscript>
// Sales transaction data from multiple sources
salesTransactions = QueryNew("transactionId,salesRep,region,product,category,quantity,unitPrice,totalAmount,customerType,saleDate",
"integer,varchar,varchar,varchar,varchar,integer,decimal,decimal,varchar,date");
QueryAddRow(salesTransactions, [
{transactionId: 1001, salesRep: "Jennifer Davis", region: "North", product: "Enterprise Software", category: "Software", quantity: 5, unitPrice: 2500.00, totalAmount: 12500.00, customerType: "Enterprise", saleDate: "2024-10-01"},
{transactionId: 1002, salesRep: "Robert Wilson", region: "South", product: "Consulting Services", category: "Services", quantity: 40, unitPrice: 150.00, totalAmount: 6000.00, customerType: "Mid-Market", saleDate: "2024-10-02"},
{transactionId: 1003, salesRep: "Amanda Taylor", region: "East", product: "Cloud Storage", category: "SaaS", quantity: 100, unitPrice: 50.00, totalAmount: 5000.00, customerType: "SMB", saleDate: "2024-10-03"},
{transactionId: 1004, salesRep: "Jennifer Davis", region: "North", product: "Training Program", category: "Services", quantity: 20, unitPrice: 300.00, totalAmount: 6000.00, customerType: "Enterprise", saleDate: "2024-10-04"},
{transactionId: 1005, salesRep: "Chris Martinez", region: "West", product: "Hardware Package", category: "Hardware", quantity: 3, unitPrice: 5000.00, totalAmount: 15000.00, customerType: "Enterprise", saleDate: "2024-10-05"},
{transactionId: 1006, salesRep: "Robert Wilson", region: "South", product: "Mobile App License", category: "Software", quantity: 50, unitPrice: 100.00, totalAmount: 5000.00, customerType: "Mid-Market", saleDate: "2024-10-06"},
{transactionId: 1007, salesRep: "Amanda Taylor", region: "East", product: "Support Contract", category: "Services", quantity: 12, unitPrice: 800.00, totalAmount: 9600.00, customerType: "Enterprise", saleDate: "2024-10-07"},
{transactionId: 1008, salesRep: "Chris Martinez", region: "West", product: "Analytics Platform", category: "SaaS", quantity: 1, unitPrice: 25000.00, totalAmount: 25000.00, customerType: "Enterprise", saleDate: "2024-10-08"},
{transactionId: 1009, salesRep: "Jennifer Davis", region: "North", product: "Integration Services", category: "Services", quantity: 60, unitPrice: 200.00, totalAmount: 12000.00, customerType: "Mid-Market", saleDate: "2024-10-09"},
{transactionId: 1010, salesRep: "Maria Rodriguez", region: "Central", product: "Security Suite", category: "Software", quantity: 10, unitPrice: 1500.00, totalAmount: 15000.00, customerType: "Enterprise", saleDate: "2024-10-10"}
]);
// Sales targets by representative
salesTargets = {
"Jennifer Davis": {"monthly": 50000, "quarterly": 150000, "territory": "North"},
"Robert Wilson": {"monthly": 45000, "quarterly": 135000, "territory": "South"},
"Amanda Taylor": {"monthly": 42000, "quarterly": 126000, "territory": "East"},
"Chris Martinez": {"monthly": 48000, "quarterly": 144000, "territory": "West"},
"Maria Rodriguez": {"monthly": 40000, "quarterly": 120000, "territory": "Central"}
};
// Product categories for analysis
productCategories = "Software,Hardware,SaaS,Services";
// Customer segments
customerSegments = ["Enterprise", "Mid-Market", "SMB"];
// Regional performance data
regionalData = QueryNew("region,targetRevenue,actualRevenue,deals,avgDealSize",
"varchar,decimal,decimal,integer,decimal");
QueryAddRow(regionalData, [
{region: "North", targetRevenue: 150000, actualRevenue: 30500, deals: 3, avgDealSize: 10166.67},
{region: "South", targetRevenue: 135000, actualRevenue: 11000, deals: 2, avgDealSize: 5500.00},
{region: "East", targetRevenue: 126000, actualRevenue: 14600, deals: 2, avgDealSize: 7300.00},
{region: "West", targetRevenue: 144000, actualRevenue: 40000, deals: 2, avgDealSize: 20000.00},
{region: "Central", targetRevenue: 120000, actualRevenue: 15000, deals: 1, avgDealSize: 15000.00}
]);
</cfscript>
<cfoutput>
<h2>📈 Sales Performance Dashboard</h2>
<div style="background: ##f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop Query Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop query="salesTransactions"><br>
<!--- Process each transaction ---><br>
</cfloop>
</div>
<h3>💰 Transaction Analysis Dashboard:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##28a745;">
<h4 style="margin-top: 0; color: ##28a745;">Real-time Sales Performance Metrics</h4>
<cfset repPerformance = {}>
<cfset categoryTotals = {}>
<cfset customerTypeTotals = {}>
<cfset totalRevenue = 0>
<cfset totalDeals = 0>
<!--- First pass: Calculate aggregations --->
<cfloop query="salesTransactions">
<cfset totalRevenue += totalAmount>
<cfset totalDeals += 1>
<!--- Sales rep performance tracking --->
<cfif NOT StructKeyExists(repPerformance, salesRep)>
<cfset repPerformance[salesRep] = {"revenue": 0, "deals": 0, "products": ""}>
</cfif>
<cfset repPerformance[salesRep].revenue += totalAmount>
<cfset repPerformance[salesRep].deals += 1>
<cfset repPerformance[salesRep].products = ListAppend(repPerformance[salesRep].products, product)>
<!--- Category analysis --->
<cfif NOT StructKeyExists(categoryTotals, category)>
<cfset categoryTotals[category] = {"revenue": 0, "deals": 0, "avgDeal": 0}>
</cfif>
<cfset categoryTotals[category].revenue += totalAmount>
<cfset categoryTotals[category].deals += 1>
<cfset categoryTotals[category].avgDeal = categoryTotals[category].revenue / categoryTotals[category].deals>
<!--- Customer type analysis --->
<cfif NOT StructKeyExists(customerTypeTotals, customerType)>
<cfset customerTypeTotals[customerType] = {"revenue": 0, "deals": 0}>
</cfif>
<cfset customerTypeTotals[customerType].revenue += totalAmount>
<cfset customerTypeTotals[customerType].deals += 1>
</cfloop>
<div style="background: ##e8f5e8; padding: 12px; border-radius: 3px; margin: 15px 0;">
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; text-align: center;">
<div style="background: white; padding: 15px; border-radius: 5px;">
<h3 style="margin: 0; color: ##28a745;">$#NumberFormat(totalRevenue, "0,000")#</h3>
<p style="margin: 5px 0 0 0;">Total Revenue</p>
</div>
<div style="background: white; padding: 15px; border-radius: 5px;">
<h3 style="margin: 0; color: ##17a2b8;">#totalDeals#</h3>
<p style="margin: 5px 0 0 0;">Total Deals</p>
</div>
<div style="background: white; padding: 15px; border-radius: 5px;">
<h3 style="margin: 0; color: ##fd7e14;">$#NumberFormat(totalRevenue/totalDeals, "0,000")#</h3>
<p style="margin: 5px 0 0 0;">Avg Deal Size</p>
</div>
<div style="background: white; padding: 15px; border-radius: 5px;">
<h3 style="margin: 0; color: ##6f42c1;">#StructCount(repPerformance)#</h3>
<p style="margin: 5px 0 0 0;">Active Reps</p>
</div>
</div>
</div>
<h5 style="margin: 15px 0 8px 0;">📋 Transaction Details:</h5>
<table style="width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 0.9em;">
<thead>
<tr style="background: ##e8f5e8;">
<th style="padding: 6px; border: 1px solid ##ddd; text-align: left;">Date</th>
<th style="padding: 6px; border: 1px solid ##ddd; text-align: left;">Sales Rep</th>
<th style="padding: 6px; border: 1px solid ##ddd; text-align: left;">Product</th>
<th style="padding: 6px; border: 1px solid ##ddd; text-align: center;">Qty</th>
<th style="padding: 6px; border: 1px solid ##ddd; text-align: right;">Amount</th>
<th style="padding: 6px; border: 1px solid ##ddd; text-align: center;">Customer</th>
</tr>
</thead>
<tbody>
<cfloop query="salesTransactions">
<tr>
<td style="padding: 6px; border: 1px solid ##ddd; font-size: 0.85em;">#DateFormat(saleDate, "mm/dd")#</td>
<td style="padding: 6px; border: 1px solid ##ddd;">#salesRep#</td>
<td style="padding: 6px; border: 1px solid ##ddd;">#product#</td>
<td style="padding: 6px; border: 1px solid ##ddd; text-align: center;">#quantity#</td>
<td style="padding: 6px; border: 1px solid ##ddd; text-align: right; font-weight: bold;">$#NumberFormat(totalAmount, "0,000")#</td>
<td style="padding: 6px; border: 1px solid ##ddd; text-align: center;">
<span style="background: #customerType EQ 'Enterprise' ? '##28a745' : (customerType EQ 'Mid-Market' ? '##fd7e14' : '##6c757d')#; color: white; padding: 2px 6px; border-radius: 10px; font-size: 0.75em;">
#customerType#
</span>
</td>
</tr>
</cfloop>
</tbody>
</table>
</div>
</div>
<h2>👤 Sales Representative Performance</h2>
<div style="background: ##f0f8ff; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop Struct Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop collection="##repPerformance##" item="rep"><br>
<!--- Analyze rep performance ---><br>
</cfloop>
</div>
<h3>🏆 Individual Performance Analysis:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##17a2b8;">
<h4 style="margin-top: 0; color: ##17a2b8;">Sales Team Performance vs. Targets</h4>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px; margin: 15px 0;">
<cfloop collection="#repPerformance#" item="rep">
<cfset repData = repPerformance[rep]>
<cfset target = salesTargets[rep].monthly>
<cfset achievement = (repData.revenue / target) * 100>
<cfset targetStatus = achievement GTE 100 ? "🎯 Target Met" : (achievement GTE 80 ? "⚡ Close" : "📈 Below Target")>
<cfset cardColor = achievement GTE 100 ? "##d4edda" : (achievement GTE 80 ? "##fff3cd" : "##f8d7da")>
<div style="background: #cardColor#; padding: 15px; border-radius: 5px;">
<h5 style="margin: 0 0 8px 0; color: ##495057;">#rep#</h5>
<div style="background: white; padding: 8px; border-radius: 3px; margin: 5px 0;">
<strong>Revenue:</strong> $#NumberFormat(repData.revenue, "0,000")# / $#NumberFormat(target, "0,000")#<br>
<div style="width: 100%; background: ##e9ecef; border-radius: 10px; height: 8px; margin: 5px 0;">
<div style="width: #Min(achievement, 100)#%; background: #achievement GTE 100 ? '##28a745' : (achievement GTE 80 ? '##fd7e14' : '##dc3545')#; height: 8px; border-radius: 10px;"></div>
</div>
<small style="color: ##666;">#NumberFormat(achievement, "0.0")#% of target</small>
</div>
<div style="background: white; padding: 8px; border-radius: 3px; margin: 5px 0;">
<strong>Deals:</strong> #repData.deals# | <strong>Avg:</strong> $#NumberFormat(repData.revenue/repData.deals, "0,000")#<br>
<strong>Territory:</strong> #salesTargets[rep].territory#
</div>
<div style="text-align: center; margin-top: 8px;">
<span style="background: #achievement GTE 100 ? '##28a745' : (achievement GTE 80 ? '##fd7e14' : '##dc3545')#; color: white; padding: 4px 8px; border-radius: 12px; font-size: 0.85em;">
#targetStatus#
</span>
</div>
</div>
</cfloop>
</div>
</div>
</div>
<h2>📊 Category & Customer Analysis</h2>
<div style="background: ##fff3cd; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop List & Struct Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop list="##productCategories##" index="category"><br>
<cfloop collection="##customerTypeTotals##" item="segment"><br>
<!--- Cross-analyze segments ---><br>
</cfloop><br>
</cfloop>
</div>
<h3>🎯 Market Segment Performance:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##fd7e14;">
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 15px 0;">
<div>
<h5 style="margin: 0 0 10px 0;">📦 Product Category Analysis</h5>
<cfloop collection="#categoryTotals#" item="category">
<cfset catData = categoryTotals[category]>
<div style="background: ##fff8e1; padding: 10px; border-radius: 3px; margin: 8px 0;">
<div style="display: flex; justify-content: space-between; align-items: center;">
<strong>#category#</strong>
<span style="background: ##fd7e14; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em;">
#catData.deals# deals
</span>
</div>
<div style="margin: 5px 0;">
Revenue: <strong>$#NumberFormat(catData.revenue, "0,000")#</strong><br>
Avg Deal: <strong>$#NumberFormat(catData.avgDeal, "0,000")#</strong>
</div>
<div style="width: 100%; background: ##f8f9fa; border-radius: 2px; height: 4px;">
<div style="width: #(catData.revenue/totalRevenue)*100#%; background: ##fd7e14; height: 4px; border-radius: 2px;"></div>
</div>
</div>
</cfloop>
</div>
<div>
<h5 style="margin: 0 0 10px 0;">👥 Customer Segment Analysis</h5>
<cfloop collection="#customerTypeTotals#" item="segment">
<cfset segData = customerTypeTotals[segment]>
<div style="background: ##f8f9fa; padding: 10px; border-radius: 3px; margin: 8px 0;">
<div style="display: flex; justify-content: space-between; align-items: center;">
<strong>#segment#</strong>
<span style="background: ##17a2b8; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em;">
#segData.deals# deals
</span>
</div>
<div style="margin: 5px 0;">
Revenue: <strong>$#NumberFormat(segData.revenue, "0,000")#</strong><br>
Avg Deal: <strong>$#NumberFormat(segData.revenue/segData.deals, "0,000")#</strong>
</div>
<div style="width: 100%; background: ##e8f4f8; border-radius: 2px; height: 4px;">
<div style="width: #(segData.revenue/totalRevenue)*100#%; background: ##17a2b8; height: 4px; border-radius: 2px;"></div>
</div>
</div>
</cfloop>
</div>
</div>
</div>
</div>
<h2>🌍 Regional Performance Analysis</h2>
<div style="background: ##f8d7da; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3>🔧 CFLoop Query Implementation:</h3>
<div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
<cfloop query="regionalData"><br>
<!--- Analyze regional performance ---><br>
</cfloop>
</div>
<h3>📍 Territory Performance Dashboard:</h3>
<div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##dc3545;">
<h4 style="margin-top: 0; color: ##dc3545;">Geographic Sales Performance Analysis</h4>
<table style="width: 100%; border-collapse: collapse; margin: 15px 0;">
<thead>
<tr style="background: ##f8d7da;">
<th style="padding: 10px; border: 1px solid ##ddd; text-align: left;">Region</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: right;">Target</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: right;">Actual</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: center;">Achievement</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: center;">Deals</th>
<th style="padding: 10px; border: 1px solid ##ddd; text-align: right;">Avg Deal</th>
</tr>
</thead>
<tbody>
<cfset totalTarget = 0>
<cfset totalActual = 0>
<cfset totalRegionalDeals = 0>
<cfloop query="regionalData">
<cfset totalTarget += targetRevenue>
<cfset totalActual += actualRevenue>
<cfset totalRegionalDeals += deals>
<cfset achievementPct = (actualRevenue / targetRevenue) * 100>
<cfset achievementStatus = achievementPct GTE 100 ? "🎯" : (achievementPct GTE 75 ? "⚡" : "📈")>
<cfset rowColor = achievementPct GTE 100 ? "##d4edda" : (achievementPct GTE 75 ? "##fff3cd" : "##f8d7da")>
<tr style="background: #rowColor#;">
<td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">#region#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: right;">$#NumberFormat(targetRevenue, "0,000")#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: right; font-weight: bold;">$#NumberFormat(actualRevenue, "0,000")#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">
#achievementStatus# #NumberFormat(achievementPct, "0.0")#%
</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">#deals#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: right;">$#NumberFormat(avgDealSize, "0,000")#</td>
</tr>
</cfloop>
</tbody>
<tfoot>
<tr style="background: ##e9ecef; font-weight: bold;">
<td style="padding: 10px; border: 1px solid ##ddd;">TOTAL</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: right;">$#NumberFormat(totalTarget, "0,000")#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: right;">$#NumberFormat(totalActual, "0,000")#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">#NumberFormat((totalActual/totalTarget)*100, "0.0")#%</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: center;">#totalRegionalDeals#</td>
<td style="padding: 10px; border: 1px solid ##ddd; text-align: right;">$#NumberFormat(totalActual/totalRegionalDeals, "0,000")#</td>
</tr>
</tfoot>
</table>
</div>
</div>
</cfoutput>
Performance considerations
Array vs. list: Iterating over an array is generally faster than iterating over a list. Lists are parsed on each iteration; arrays provide direct indexed access. Prefer array when the data is or can be structured as an array.
File loops: Looping over a file does not load the entire file into memory. ColdFusion reads line-by-line or in character chunks, which is suitable for large files. Use the characters attribute to control chunk size when reading by characters.
Avoid queries inside loops: Running cfquery inside a cfloop (N+1 pattern) can cause many database round-trips. Prefer a single query with appropriate WHERE/JOIN logic, or batch operations where possible.
Large collections: For CPU-bound work on large arrays, consider arrayEach() or arrayMap() with parallelization (parallel=true) instead of cfloop, which runs sequentially.
Struct iteration: Iteration order over structs is not guaranteed. For ordered processing, convert to an array or use a different structure if order matters.

