php - 如果动态变量相同

php - if dynamic variables are identical

我从我的数据库中获取一堆记录并循环遍历它们:

$sql = "SELECT * FROM driving_list_shipments WHERE id IN($allIds)";
$stmt = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
foreach($stmt as $row){ 

}       

现在,我的 $row[] 包含以下内容:

$row["id"]; //Row id from database table
$row["temperature"]; //Values can be: 2-8, 15-25, No Temperature
$row["dgr"]; //Values can be: 0,1
$row["eq"]; //Values can be: 0,1
$row["ice"]; //Values can be: 0,1
$row["pil"]; //Values can be: 0,1

显然,以上条件可以做出很多不同的组合。我想弄清楚如何将具有 exact 相同条件的记录添加到它们各自的数组中。

示例 #1: 如果行 ID 10、20 和 30 具有 $row["dgr"] = "1"$row["temperature"] = "2-8",那么我希望将这些记录添加到数组中(因为它们都具有相同的条件)。

我不确定如何进行检查,因为我不能 $condition1 = $condition2,因为有数百种不同的结果。

示例 #2:

if($row["dgr"] == 0 && $row["eq"] == 1){ 
  echo $row["id"]; //Show the ids that matches above condition 
}
if($row["dgr"] == 1 && $row["eq"] == 0){ 
  echo $row["id"]; //Show the ids that matches above condition 
}    
if($row["dgr"] == 0 && $row["eq"] == 0){ 
  echo $row["id"]; //Show the ids that matches above condition 
}

正如您在上面看到的,这些只是一些可能的组合。如果我必须 "manually" 检查所有 5 个条件和数百种不同的组合,那将花费我很长时间。

您可以通过编写查询而不是在 PHP 循环中检查它们来获取它们。

$sql = "SELECT * FROM driving_list_shipments WHERE id IN($allIds) AND dgr='1' AND temperature='2-8'";

或者实际上我的意思是写一个循环来为您抓取正确的数据而不是遍历所有数据:

$rules = array (
  array ('dgr' => '1', 'temperature'=> '2-8'),
  array ('dgr' => '0', 'temperature'=> '2-8')
);   
for ($rulse as $rule) {
  $sql = "SELECT * FROM driving_list_shipments WHERE id IN($allIds) AND dgr='".$rule['dgr']."' AND temperature='".$rule['temperature']."'";
  $stmt = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}

这可能不是您想要的,但您可以在查询中使用 GROUP BY andgroup_concat` 来实现此目的:

SELECT `temperature`,`dgr`,`eq`,`ice`,`pil`, GROUP_CONCAT(`id`) as `ids` FROM `driving_list_shipments` WHERE id IN($allIds) GROUP BY `temperature`,`dgr`,`eq`,`ice`,`pil`

然后你使用explode将ids变成一个数组,例如

explode(',', $row['ids'])

此查询将为您提供哪些 ID 与特定温度和 dgr 相匹配的结果。或许这样的结果可以查询过来。并分配给特定的变量。

SELECT temperature, dgr, GROUP_CONCAT(id) as ids FROM driving_list_shipments WHERE id IN($allIds) GROUP BY temperature, dgr