Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with creating an array of structs

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...
like image 645
Phil Avatar asked Feb 22 '23 09:02

Phil


1 Answers

You didn't show the entire code.

I suspect replacing what you did show with either of these will solve the problem:

<cfset local.posts = VARIABLES.postDao.getBlogPosts(argumentCollection=arguments) />
<cfset local.result = arraynew(1) />

<cfloop index="local.i" from="1" to="#arrayLen(local.posts)#">
    <cfset local.post = local.posts[local.i].getInstance()>
    <cfset StructInsert(local.post, 'comments', getComments(local.post.postId))>
    <cfset ArrayAppend(local.result, local.post)>
</cfloop>


Or:

<cfset var posts = VARIABLES.postDao.getBlogPosts(argumentCollection=arguments) />
<cfset var result = arraynew(1) />
<cfset var i = 0 />
<cfset var post = 0 />

<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>


You should always use either var keyword or local scope for variables in a cffunction.

You can use VarScoper to check your code for other places where this needs fixing.

like image 96
Peter Boughton Avatar answered Mar 02 '23 18:03

Peter Boughton