I'm making a blog API and am having some very strange issues when trying to create an array of structs in coldfusion. The top level array will contain the post, as a struct, with a .comments that is an array of all comments under that post, also as structs.
Each of the pieces in the following code work individually. But, somehow when I put them together I end up with an infinitely nested array of structs containing an array of structs etc... all of only the very last element in the top level array of posts.
<cfset posts = VARIABLES.postDao.getBlogPosts(argumentCollection=arguments) />
<cfset result = arraynew(1) />
<cfloop index="i" from="1" to="#arrayLen(posts)#">
<cfset post = posts[i].getInstance()>
<cfset StructInsert(post, 'comments', getComments(post.postId))>
<cfset ArrayAppend(result, post)>
</cfloop>
getBlogPosts returns an array of Post beans.
bean.getInstance() returns a struct with all the data in the bean.
getComments(id) returns an array all comments(structs) for post[id].
Each of these works as intended and is used elsewhere without problems.
The structure of the infinitely nested array is as such:
Array containing Post
. Post.comments containing array of comments + Post on end
. . Post.comments containing array of comments + Post on end
. . . etc...
variablesscope, so every function in that component is accessing the same variables. So as you loop through calling more functions, your initial variables are being overwritten each time. When you use the var keyword, it puts them into thelocalscope, and each function has its own local scope that exists only within that function.