获取行并检查是否具有相同的值

时间:2018-11-20 03:04:26

标签: php mysql compare fetch

我是编码和尝试学习PHP和MYSQL的新手。我想做的是,在进行回显的同时将相同的CustomerID查询分组在同一张表中。此刻,我的代码回显了所有单独的查询。我有一张桌子

ID      CustomerID     DATE        Company
1           1       2018-11-19        A
2           1       2018-11-19        A
3           2       2018-11-19        B
4           3       2018-11-19        C
5           4       2018-11-19        D
6           4       2018-11-19        D

我的代码

$query = "SELECT `customers`.ID, `customers`.customerid, `customers`.date
        FROM `customers` WHERE month(DATE)= month(CURRENT_DATE()) AND YEAR(DATE) = YEAR(CURRENT_DATE());

$result = $mysqli->query($query);

while($resultquery = $result->fetch_array())

{
$queryresult[] = $resultquery;

}
if (!empty($queryresult)) {

foreach($queryresult as $queryresults)
{

$id = $queryresults['id'];
$customerid = $queryresults['customerid'];  
$date = $queryresults['date'];
?>

然后我回显它,结果是

Company Name: A
ID CustomerID DATE
1      1    2018-11-19

Company Name: A
ID CustomerID DATE
2      1    2018-11-19

Company Name: B
ID CustomerID DATE
3      2    2018-11-19

Company Name: C
ID CustomerID DATE
4      3    2018-11-19

<?php }} ?>

等等。

但是我想要比较的是customerID,如果有多个具有相同ID的客户ID,请将它们作为表中的组进行回显。

Company Name: A
ID CustomerID DATE
1      1    2018-11-19
2      1    2018-11-19

Company Name: B
ID CustomerID DATE
3      2    2018-11-19

Company Name: C
ID CustomerID DATE
4      3    2018-11-19

我使用GROUP_CONCAT进行了sql查询,并使用SEPARATOR'|')对结果进行分组,它可以工作,但我认为实现此目标不是最好的,所以请帮忙。谢谢

1 个答案:

答案 0 :(得分:1)

公司作为键(在查询中包括公司:

)在键值数组中映射数据

$ query =“ SELECT connect。ID,customers。customerid,customers。date,公司         从customers开始,其中month(DATE)= month(CURRENT_DATE())AND YEAR(DATE)= YEAR(CURRENT_DATE())“;

customers

然后使用一个键对项目进行分组来简化数据收集:

$query = "SELECT `customers`.ID, `customers`.customerid, `customers`.date
        FROM `customers` WHERE month(DATE)= month(CURRENT_DATE()) AND YEAR(DATE) = YEAR(CURRENT_DATE());

然后您可以使用foreach呈现信息:

$result = $mysqli->query($query);
$queryresult = [];
while($resultquery = $result->fetch_array())

{
 $company = $resultquery['company'];
 if (array_key_exists($company,$queryresult){
   @$queryresult[$company] = [];
 }
 @$queryresult[$company][] = $resultquery;

}