我知道在PHP Activerecord中,你可以将条件数组作为:
// Data Structure
['a=? && b=?', 'foo', 'bar']
// Outputs:
// SELECT * FROM `table` WHERE `a`="foo" && `b`="bar"但是我在程序的另一部分生成了一个关联数组,我想将其作为直接条件传递。列可能会发生变化,所以我不能提前编写查询字符串,所以可以传入一个键/值对的关联数组作为条件吗?我想不起来我是不是对此有意见。我没有看到任何说明标准关联数组是允许的结构的文档。
// Data Structure
['a' =>'foo', 'b' => 'bar']
// Outputs:
// SELECT * FROM `table` WHERE `a`="foo" && `b`="bar"最后,两种方法之间的条件是否可以混合?我还有一些条件需要与键/值对一起传递。
// Data Structure
['(a=? || b=?)', 'foo', 'bar', 'c' => 'baz']
// Outputs:
// SELECT * FROM `table` WHERE (`a`="foo" || `b`="bar") && `c`="baz"这在PHP Activerecord中是可能的吗,而且-它是一个安全/可靠的操作吗?
发布于 2014-05-31 00:45:44
我写这篇文章只是为了确保一致的行为。语法为:
mixedConditions($associativeArray, $statement = '', ...$parameters);用起来像..。
mixedConditions(['a'=>'foo', 'b'=>'bar'],'`c`=? && `d`=?','baz','qux');它将输出一个包含以下内容的数组
Array
(
[0] => `a` = ? && `b` = ? && `c`=? && `d`=?
[1] => foo
[2] => bar
[3] => baz
[4] => qux
)函数:(未测试)
function mixedConditions ($assoc, $statement = '')
{
$conditions = [];
$statementConditions = array_slice(func_get_args(),2);
foreach ($assoc as $key => $value)
if (is_array($value))
$conditions[] = '`'.preg_replace('#[^a-z0-9\-_]#i','',$key).'` IN (?)';
else
$conditions[] = '`'.preg_replace('#[^a-z0-9\-_]#i','',$key).'` = ?';
if (!empty($statement))
return array_merge([implode(' && ', array_merge($conditions, [$statement]))], array_values($assoc), $statementConditions);
else
return array_merge([implode(' && ', $conditions)], array_values($assoc));
}注意:该函数将删除参数名称中的外来字符。
如果Activerecord有更好的或内部的方法来做这件事,请让我知道,我仍然会选择你的答案。
https://stackoverflow.com/questions/23959014
复制相似问题