显示具有一对多关系的php mysql查询结果 [英] displaying php mysql query result with one to many relationship

查看:211
本文介绍了显示具有一对多关系的php mysql查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一个示例表:

info table
info_id     name  
1           john  
2           peter
------------------------  
details table  
details_id      log                               date  
1            test log for john                  2013-08-01  
1            another log for john               2013-08-02  
2            test log for peter                 2013-08-02

这是我的示例查询:

SELECT info.info_id, info.name, details.details_no, details.log, details.date 
FROM info JOIN details ON details.details_id = info.info_id 
GROUP BY info.info_id  

这是我想要实现的显示:

And Here's display i want to achieve:

john  
1     test log for john            2013-08-01  
1     another test log for john    2013-08-02  

peter  
2     test log for peter           213-08-02  

我尝试过使用foreach循环,然后在第一个循环内执行另一个foreach循环.

I have tried using foreach loop and then execute another foreach loop inside the first loop.

请帮助伙计们

推荐答案

您可能将不得不获取数据并创建所需的数组.

You are probably going to have to take the data and make the array that you want.

$data = array();
foreach ($result as $item) {
    $key = $item['name']; // or $item['info_id']
    if (!isset($data[$key])) {
        $data[$key] = array();
    }

    $data[$key][] = $item;
}

// Build your table with the new $data array

编辑

这只是一个例子.正如amaster507指出的那样,如果您的name字段不是唯一的,则需要在唯一键上构建数组.与此没有太大的不同,因为您可能只是将$item['name']的实例更改为$item['info_id'].

This is just an example. As amaster507 points out, if your name field isn't unique, you will need to build your array on a unique key. Not terribly different from this, as you could probably just change instances of $item['name'] to $item['info_id'].

这篇关于显示具有一对多关系的php mysql查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆