PHP分组重复 - 只显示一次

时间:2015-04-19 08:20:10

标签: php mysql

我的数据库

table:tree_hie

urutan_cluster | kd_barang
31             | X | Y | Z | A
32             | X | Y | Z | A
33             | X | Y | Z | A | B
33             | X | Y | Z | A | B | C | D

表:pergerakan

kd_barang | pnaik
x         | 4
y         | 3
z         | 3
a         | 3
b         | 2
c         | 1
d         | 1

查询表

CREATE TABLE tree_hie
    (`urutan_cluster` int, `kd_barang` varchar(9))
;  
INSERT INTO tree_hie
    (`urutan_cluster`, `kd_barang`)
VALUES
    (31, ' X | Y | Z | A '),
    (32, ' X | Y | Z | A '),
    (33, ' X | Y | Z | A | B'),
    (34, ' X | Y | Z | A | B | C | D')
;
CREATE TABLE value
    (`id` varchar(1), `value` int)
;  
INSERT INTO pergerakan
    (`kd_barang`, `pnaik`)
VALUES
    ('x', 4),
    ('y', 3),
    ('z', 3),
    ('a', 3),
    ('b', 2),
    ('c', 1),
    ('d', 1)
;

我仍在为这些家伙编码

    <table border="1" cellpadding="3">                                                                                                     
    <tr>
        <th  style="text-align:center;">A</th>
        <th  style="text-align:center;">B</th>
    </tr>
<tbody>
<?php 

    $sqlp=mysql_query("SELECT * FROM tree_hie group by urutan_cluster");

    while ($data1=mysql_fetch_array($sqlp)){
       $clusters = $data1['urutan_cluster'];
    echo '<tr>';
    echo '<td style="width:90px;text-align:center;">'.$clusters.'</td>';   

    $sql2 = mysql_query("SELECT * FROM tree_hie where urutan_cluster = '$clusters'") or die(mysql_error());

            while ($data2 = mysql_fetch_array($sql2)) {

                $urutan = $data2['urutan_cluster'];             
                $item_explode = explode('|', $item);

                foreach($item_explode as $items)
                {
                        $sql3 = mysql_query("SELECT * FROM pergerakan where kd_barang = '$items'") or die(mysql_error());

                                while ($data3 = mysql_fetch_array($sql3)) {

                                        $naik = $data3['pnaik'];

                                        echo '<td style="width:90px;text-align:center;">'.$naik.'</td>';  
                                }

                }
}

    echo '</tr>';
    }
    ?>
    </tbody>
    </table>

伙计..如果我有这样的代码,就像这样显示..

31  4   3   3   3
32  4   3   3   3
33  4   3   3   3   2
34  4   3   3   3   2   1   1

但我想要这样的群组,每个重复的号码只显示一次

31  4   3
32  4   3   
33  4   3   2
34  4   3   2   1

我不知道这是怎么回事......你可能认识这些人吗?谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

$item_explode转换为可与IN一起使用的列表,然后使用DISTINCT获取没有重复的结果:

$in_list = implode(', ', array_map(function($x) {
    return "'" . mysql_real_escape_string($x) . "'";
}, $item_explode));

$sql3 = mysql_query("SELECT DISTINCT pnaik FROM pergerakan WHERE kd_barang IN ($in_list)");