选择 CSV 字符串中 ID 的位置 - 如果缺少行,如何执行某些操作



我有一个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"];
}
}

此代码不是查看找到的记录,而是首先在 id 上键入检索到的记录,然后查看您要查找的 ID,如果未找到此记录(使用isset()(,则处理未找到的部分...

$arr = array_column($arr, null, "id");
$ids = explode(",", $str);
foreach($ids as $el){
if(!isset($arr[$el]))   {
echo 'the row is missing';
}  else{
echo 'the row is there';
}
}

最新更新