我一直在和开发人员讨论下面的代码。它是一个函数,它将采用标量整数或标量整数的一维数组作为$ comment_id。目标是将诸如$comment_id = 16;
或$comment_id = '16';
或$comment_id = array(1, '2', 3, '4', 5, ...)
或$comment_id = array(1, '2', 3, '4', 5, ...)
之类的东西转换为$id_string = '1, 2, 3, 4, 5';
$ id_string将在SQL WHERE NOT IN子句中用于从结果中排除某些主键。该功能将在我们的应用程序中广泛使用,所以重要的是它运行速度快,但出于安全原因也是完整的。PHP使用完整性令牌化逗号列表的最简单方法
鉴于上面的例子,我问1.这个函数将做我已经完成的任务,2.如果没有,那么你可以提供一个替代方案。感谢您的时间。
代码:
public function int_or_array_to_comma_list($comment_id)
{
if(! is_array($comment_id))
{
if(! is_numeric($comment_id)) throw new Exception();
$comment_id = intval($comment_id);
// is $comment_id a integer?
if($comment_id === 0) throw new Exception();
$values = array($comment_id);
}
else
{
$values = $comment_id;
}
if(empty($values)) throw new Exception();
$id_string = '';
for($i = 0; $i <= count($values); $i++)
{
// does the passed array keys follow the 0, 1, 2, 3, 4, 5, ... pattern?
if(! isset($values[$i]) OR ! is_numeric($values[$i])) throw new Exception;
$values[$i] = intval($values[$i]);
// is $comment_id a integer?
if(0 === $values[$i]) throw new Exception();
// build comma list, if final array value exlude comma
$id_string .= ($i !== count($values))? $values[$i] . ', ' : $values[$i];
}
return $comment_id;
}
但你从来没有辩论过代码缩进? – bitWorking
这是很好的缩进,我粘贴在这里然后手动在每一行放置四个空格。这毁了格式。我试图添加更多的空间来纠正缩进,但我收到了系统消息,说它看起来不像代码。 –
@MichaelRich。 。 。这与MySQL无关,因此我将删除标签。 –