programing

SQL의 값 배열에 따라 존재하는 값과 존재하지 않는 값 배열

coolbiz 2023. 1. 27. 21:54
반응형

SQL의 값 배열에 따라 존재하는 값과 존재하지 않는 값 배열

제목이 생각나지 않았어요. 안 좋은 거 알아요.

기본적으로는 일련의 가치관을 POST합니다.이 값은 정수가 됩니다.

1, 2, 3, 4, 5 등이라고 칩시다.나는 이미 데이터베이스에서 그들의 각각의 가치를 얻는 방법을 알아냈다.

  $values = explode(",", $_GET['id']);
  $placeholders = str_repeat('?, ', count($values) - 1) . '?';
  $CheckQuery = $database->prepare("SELECT * FROM users WHERE the_id IN($placeholders)");
  $CheckQuery->execute($values);
  $Res = $CheckQuery->fetchAll(PDO::FETCH_ASSOC);

ID를 지정하면 다음 ID를 반환할 수 있기 때문에 매우 좋습니다.

ID1:0or1
ID2:0or1

데이터베이스에 존재하지 않는 ID를 어떻게 반환해야 할지 고민하고 있습니다.도와줄 사람 있어?

1 또는 0을 원하는 경우 다음 결과를 사용할 수 있습니다.$values어레이와 데이터베이스의 데이터$Res, 이러한 리스트에 키 입력된 어레이를 작성합니다(용도 1).$Res의 경우는 0 입니다.$values)는 0을 데이터베이스에 있는 1로 덮어씁니다.

$present = array_fill_keys(array_column($Res, 'the_id'), 1);
$allValues = array_fill_keys($values, 0);
$result = array_replace($allValues, $present);

테스트 데이터...

$_GET['id'] = '1,2,3';
$values = explode(",", $_GET['id']);

$Res = [ ['the_id' => 1], ['the_id' => 3]];

$present = array_fill_keys(array_column($Res, 'the_id'), 1);
$allValues = array_fill_keys($values, 0);
$result = array_replace($allValues, $present);

print_r($result);

얻을 수 있다

Array
(
    [1] => 1
    [2] => 0
    [3] => 1
)
$values = explode(",", $_GET['id']);
$placeholders = str_repeat('?, ', count($values) - 1) . '?';
// select `the_id` as you don't need other fields in select
$CheckQuery = $database->prepare("SELECT the_id FROM users WHERE the_id IN($placeholders)");
$CheckQuery->execute($values);

// Use `FETCH_COLUMN` to fetch ids as array:
$ids = $CheckQuery->fetchAll(PDO::FETCH_COLUMN, 0);
// Now you can use `array_diff` to get ids 
// that are in `$values` and not in `$ids`
print_r(array_diff($values, $ids));

언급URL : https://stackoverflow.com/questions/60613390/array-of-values-from-sql-showing-which-exist-and-which-dont

반응형