我有一个csv字符串,需要选择具有相应ID的行。
如果行不存在,则需要做一些特定的事情。
$str = '1,2,3,4,5,6,7,8,9,10,11,12';
$st = $db->query("select *
from arts
where id in (" . $str . ")
order by field (id, " . $str . ")");
$arr = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($arr as $el) {
// if ($el is missing) {echo 'the row is missing';} // how to do this?
else { ... }
}
最佳答案
假设您对输入的CSV字符串感到困惑,这里最简单的选择是使用FIND_IN_SET
,如下所示:
$sql = "SELECT id, FIND_IN_SET(id, :list) AS result FROM arts";
$str = "1,2,3,4,5,6,7,8,9,10,11,12";
$stmt = $db->prepare($sql);
$stmt->bindParam(':list', $str);
$stmt->execute();
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($arr as $el){
if ($el["result"] <= 0) {
echo "the row is missing for id " . $el["id"];
}
}
关于php - 选择csv字符串中id的位置-如果缺少行怎么办,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59437947/