Phi*_*hil 4 coldfusion multidimensional-array
我正在制作一个博客API,并且在尝试在coldfusion中创建一个结构数组时遇到一些非常奇怪的问题.顶级数组将包含作为结构的帖子,其中.comments是该帖子下所有注释的数组,也是结构.
以下代码中的每个部分都单独工作.但是,不知何故,当我把它们放在一起时,我最终会得到一个无限嵌套的结构数组,其中包含一个结构数组等...所有这些只是帖子顶级数组中的最后一个元素.
<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>
Run Code Online (Sandbox Code Playgroud)
getBlogPosts返回一个Post bean数组.
bean.getInstance()返回一个包含bean中所有数据的结构.
getComments(id)返回一个数组post [id]的所有注释(结构).
这些中的每一个都按预期工作并且在其他地方使用而没有问
无限嵌套数组的结构如下:
Array containing Post
. Post.comments containing array of comments + Post on end
. . Post.comments containing array of comments + Post on end
. . . etc...
Run Code Online (Sandbox Code Playgroud)
您没有显示整个代码.
我怀疑用这些中的任何一个替换你所做的显示将解决问题:
<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>
Run Code Online (Sandbox Code Playgroud)
要么:
<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>
Run Code Online (Sandbox Code Playgroud)
对于cffunction中的变量,
应始终使用var关键字或局部范围.
您可以使用VarScoper检查您需要修复的其他地方的代码.
| 归档时间: |
|
| 查看次数: |
3988 次 |
| 最近记录: |