2017-07-24 69 views
1

我已经在这里得到一个不同的列值和其他列具有相同名称的所有值

  name_relation  
[ id  name  age  head ] 
[ 1  X1  12  X ] 
[ 2  X2  22  X ] 
[ 3  X3  54  X ] 
[ 4  Y1  4  Y ] 
[ 5  Y2  8  Y ] 
[ 6  Y3  10  Y ] 

这个表我想要得到的是以下

X: X1X2X3 
Y: Y1Y2Y3 

所以我做了这个循环

$pre = null; 
$ed = ""; 
while($row = $stmt->fetch()){ 
    $name = $row['name']; 
    $head = $row['head']; 

    if ($head != $pre) { 
     echo $ed; 
     echo "<div>"; 
     echo "$head:"; 
    } 
    $ed = "</div>"; 
    $pre = $head; 
    echo $name; 
} 
echo $ed; 
echo "</div>"; 

在一个空的页面它工作完美,但是当我把它与另一个代码结构我发现,网页浏览器被灌和自动修复它,但现在我在循环结束时获得额外的</div>,我怎么能解决这个循环成为

<div> 
    X:X1X2X3 
</div> 
<div> 
    Y:Y1Y2Y3 
</div> 
+0

你使用什么数据库系统?从数据库中获取已经组合的值比较容易。 – axiac

+0

@axiac MYSQL(MariaDB) – Axon

回答

2

虽然是可能的,并不难达到你想要的使用PHP的结果,使用适当的查询,您的问题在数据库中更容易解决。

试试这个:

SELECT head, GROUP_CONCAT(name SEPARATOR '') AS all_names 
FROM tbl 
GROUP BY head 

替换tbl与实际的表名。您可能也希望以某种顺序得到结果。为此添加ORDER BY head

的PHP代码现在变为:

while ($row = $stmt->fetch()) { 
    echo("<div>{$row['head']}:{$row['all_names']}</div>"); 
} 

这就是全部。


的PHP,唯一的解决办法就是保持head当前值的轨道, 输出关闭标签</div>head值更改但不是第一排,输出的开始标记<div>之前也当值head发生变化时。此外,只显示一次head的值,当它更改时,将显示每行的值name。不要忘记在循环结束后输出一个结束标记,但只有在迭代至少一次时(查询才返回)。

这听起来很困难,但其实是很容易的:

// The current value of $['head'] 
// We assume here NULL is not a valid value for it in the database 
// If it happens that you have NULLs in the database in column "head" 
// then make sure the query converts it to an empty string. For example: 
//  SELECT IFNULL(head, '') AS head ... 
$head = NULL; 
// Process one row at a time 
while ($row = $stmt->fetch()) { 
    if ($row['head'] !== $head) { 
     // The value of 'head' just changed 
     // Display '</div>' but not before the first row 
     if ($head !== NULL) { 
      // This is not the first row, there is a current value of 'head' 
      echo("</div>\n"); 
     } 
     // Display the opening tag '<div>' and new value of 'head', only once 
     echo("<div>{$row['head']}: "); 
     // Update the current value of 'head' 
     $head = $row['head'] 
    } 
    // Display 'name'; there is nothing special here 
    echo($row['name']); 
} 

// After the loop, close the last <div> only if there is one ($head was changed) 
if ($head !== NULL) { 
    echo("</div>\n"); 
} 

而不是在上面的代码,你可以使用一些“神奇”的字符串NULL(它被称为“前哨”),这是不可能的出现在数据库的head列中。

+0

我添加了我用过的查询,你可以在这个解决方案上应用它吗?因为我期望解决'循环'本身,但你的答案似乎很容易和有效的使用,如果可能的话,你可以解释一下,'GROUP BY'在这里停止重复吗? – Axon

+0

'JOIN'不会有太大变化。只要将它视为“FROM”子句的一部分即可。假设在一个表上的原始查询是'SELECT head,name FROM tbl',我相信你可以很容易地找出如何更新我建议的查询来回答匹配你的实际查询。 – axiac

+0

我可以从'GROUP_CONCAT()'获取两个值吗?就像我有另一个像'age'这样的列,并且我想'echo'这个'name'与它的'age'像这样'X:X1(12)X2(22)X3(54)'Y:Y1(4 )Y2(8)Y3(10)'我能用第一种方法实现吗? – Axon

相关问题