PHP MySQL - 检测数组查询中是否缺少行

时间:2017-12-07 08:21:02

标签: php mysql

我正在查找一系列值。每当在数据库中找不到查找数组中的值时,我想在结果数组中将值设置为" notFound"。

我将如何做到这一点?

代码:

$sql = "SELECT country FROM customers WHERE name IN ('Adam', 'David', 'Frank', 'Mike')";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $countryArray[] = $row['country'];
    }
} 

当前输出:

+----- -+---------+
| Name  | Country |
+------------+----+
| Adam  |      UK | 
| David |      AU | 
| Mike  |      CN | 
+-------+---------+

期望的输出:

+----- -+-------------+
| Name  |     Country |
+------------+--------+
| Adam  |          UK | 
| David |          AU | 
| Frank |     NotFound| 
| Mike  |          CN | 
+-------+-------------+

在上面的示例中,如果在数据库中找不到frank,我希望结果数组返回" NotFound"。

2 个答案:

答案 0 :(得分:0)

不是最有效/优雅,但应该有效。假设您的$names数组包含与DB完全相同的名称(区分大小写)。

$names = array('Adam', 'David', 'Frank', 'Mike');
$not_found_array = array_fill_keys($names, 'NotFound');

$sql = "SELECT name, country FROM customers WHERE name IN ('".implode("','", $names)."')";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $countryArray[$row['name']] = $row['country'];
    }
}

$countryArray = array_merge($not_found_array, $countryArray);

答案 1 :(得分:0)

您可以尝试以下代码。

$sql = "SELECT name, country FROM customers WHERE name IN ('Adam', 'David', 'Frank', 'Mike')";
$result = $conn->query($sql);
$nameArray = array("Adam","David","Frank","Mike");
$dataArray = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $dataArray["Name"][] = $row['name'];
        $dataArray["Country"][$row['name']] = $row['country'];
    }
}

echo 'Name|Country'; 
foreach($nameArray as $val)
{
    echo $val.'|'.((empty($dataArray[$val]))?'Not Found':$dataArray[$val]); 
    // There you can also assign a array for the same.
}