我从我的数据库中获取了一堆记录,并循环遍历它们:
$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
显然,上述条件可以形成许多不同的组合。我试图弄清楚如何将具有完全相同条件的记录添加到各自的数组中。
示例1:如果第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
}
正如您在上面看到的,这些只是一些可能的组合。如果我必须“手动”检查所有5个条件和数百个不同的组合,它将花费我永远。
发布于 2018-06-03 12:20:16
这可能不是您想要的结果,但是您可以在查询中使用GROUP BY and
group_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'])
发布于 2018-06-03 12:13:29
您可以通过编写查询来获得它们,而不是在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);
}
发布于 2018-06-03 12:21:40
此查询将提供一个与特定温度和dgr匹配的id的结果。也许这件事的结果是可以质疑的。并被分配给一个特定的变量。
SELECT temperature, dgr, GROUP_CONCAT(id) as ids FROM driving_list_shipments WHERE id IN($allIds) GROUP BY temperature, dgr
https://stackoverflow.com/questions/50666145
复制相似问题