我需要像这样从数据库中打印标签 id:'1','2','3'
.我有这个代码:
$_POST['tags'] = "1,2,3";
$arr_tag = explode(",", $_POST['tags']);
$arr_tag = str_replace(' ', '-', $arr_tag);
foreach($arr_tag as $tag)
{
$__SQL__ = data::FETCH("SELECT id FROM " . TAGS . " WHERE name = ?", $tag);
$tags_id[] = $__SQL__[0]['id'];
$quoted_tags = array_map(function ($x){ return "'$x'";}, $tags_id);
$string = implode(',', $quoted_tags);
echo $string;
}
输出为:
'126''126','303''126','303','308'
在操作中$_POST['tags'] = "1,2,3";
有 3 个数组值,但在输出中我看到 6 个值:'126''126','303''126','303','308'
.
我该如何解决这个问题?
问题是你在循环中做array_map
和implode
。因此,每次您看到结果的运行列表时。循环完成后,您应该只执行一次:
foreach($arr_tag as $tag)
{
$__SQL__ = data::FETCH("SELECT id FROM " . TAGS . " WHERE name = ?", $tag);
$tags_id[] = $__SQL__[0]['id'];
}
$quoted_tags = array_map(function ($x){ return "'$x'";}, $tags_id);
$string = implode(',', $quoted_tags);
echo $string;