我有PHP代码,它使用foreach循环来循环并创建查询。我试图将其转换为ColdFusion,但我迷路了。有人能说明如何做到这一点吗?
if ($deps) {
$num = count($deps);
$i = 0;
$addon = " AND (";
foreach ($deps as $dep) {
$addon .= " DEPARTMENT_ID='{$dep['dep']}'".($num != ++$i ? ' OR': '');
}
$addon .= ")";
} else {
// Has been assigned no departments, so they can't see any tickets
$addon = " AND (DEPARTMENT_ID='-1')";
}
答案 0 :(得分:5)
这是PHP将直接翻译成CFML,即:只需要很少的更改以使其编译和运行:
<cfscript>
if (isDefined('$deps')) {
$num = ArrayLen($deps);
$i = 0;
$addon = " AND (";
for ($dep in $deps) {
$addon &= " DEPARTMENT_ID='#$dep['dep']#'"&($num NEQ ++$i ? ' OR': '');
}
$addon &= ")";
} else {
// Has been assigned no departments, so they can't see any tickets
$addon = " AND (DEPARTMENT_ID='-1')";
}
</cfscript>
以下是差异的屏幕截图,显示了已发生的变化:
变化是:
foreach ( Y as X )
转换为for ( X in Y )
&
和&=
进行连接,而不是.
和.=
{braces}
- 对于单个变量,它可能直接$varname
并且将被评估。在CFML中,您使用#hashes#
将变量的值放在字符串中。请注意,CF允许您在脚本中使用!=
,但NEQ
必须在基于标记的代码中使用(cfif / cfset)。
另请注意,虽然PHP要求变量以$
符号开头,但CFML并不关心任何方式,因此不需要删除它们(即使它们是丑陋的噪音)。
这是以更简单的方式完成的相同概念:
<cfscript>
if ( NOT isDefined('deps') )
deps[1] = {dep=-1};
addon = [];
for ( dep in deps )
ArrayAppend(addon," DEPARTMENT_ID='#dep.dep#'");
addon = " AND (#ArrayToList(addon,' OR')#)";
</cfscript>
以下是类似代码如何与cfqueryparam一起使用的示例:
<cfscript>
if ( isDefined('deps') )
{
depIds = [];
for ( dep in deps )
ArrayAppend(depIds,dep.dep);
}
else
{
depIds = [-1];
}
</cfscript>
<cfquery>
...
<cfif ArrayLen(depIds) >
AND DEPARTMENT_ID IN (<cfqueryparam list value=#ArrayToList(depIds)# cfsqltype="cf_sql_integer" />)
</cfif>
</cfquery>
(正确的代码当然会使用更好的变量名和适当的范围。)
答案 1 :(得分:3)
忘记php代码。看起来它正在寻找这样的东西:
and (
department_id = value1
or
department_id = value1
etc
)
相反,请尝试创建这样的内容:
and departent_id in
(<cfqueryparam cfsqltype="cf_sql_integer" value="#SomeList#" list="yes">)
您可以使用条件逻辑来创建SomeList变量。它可以是“1,3,5”或“-1”,具体取决于$ deps变量的ColdFusion等价物。
答案 2 :(得分:1)
我喜欢Dans解决方案,但这里的代码已翻译为CF:
<cfif IsDefined('deps')>
<cfset num = ArrayLen(deps)>
<cfset i = 0>
<cfset addon = " AND (">
<cfloop array="#deps#" index="dep">
<cfset addon &= " DEPARTMENT_ID='#dep#'" & num NEQ ++i ? ' OR': ''>
</cfloop>
<cfset addon &= ")">
<cfelse>
<cfset addon &= " AND (DEPARTMENT_ID='-1')">
</cfif>