PHP/MySQL - 将两个表组合成一个数组 [英] PHP/MySQL - Combining two tables in an array

查看:53
本文介绍了PHP/MySQL - 将两个表组合成一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是 SQL 菜鸟.我的桌子是这样的:

SQL Noob here. My table is like this:

主表

+-----------+-------------+
| talent_id | talent_name |
+-----------+-------------+
|         1 | Talent1     |
|         2 | Talent2     |
|         3 | Talent3     |
+-----------+-------------+

教育表

+-----------+-----------+-----------------------------+
| talent_id |   level   |           course            |
+-----------+-----------+-----------------------------+
|         1 | Post-Grad | Master in Something         |
|         1 | Post-Grad | Doctor in Something         |
|         1 | College   | BS Something Engineering    |
|         2 | College   | BS Something Science        |
|         2 | Post-Grad | Master in Something Science |
|         3 | College   | BS Computer Something       |
+-----------+-----------+-----------------------------+

是否可以在一个查询中组合两个表中的列?我尝试过单独的查询(顺便说一下,这很有效),但是我很难将这两个查询组合到一个数组中.如果以防万一有单独的查询是更好的解决方案,你们能给我一个想法如何遍历两个数组结果并将其组合成这样的:

Is it possible to combine the columns from the two tables in one query? I tried having separate queries (which worked, by the way) but I am having a hard time combining those two in an array. And if just in case that having separate queries is the better solution, Can you guys give me an idea how to iterate through the two array results and combine it into something like this:

Array( [0] => Array(
             'talent_id' => '1', 
             'talent_name' => 'Talent1', 
             'course' => Array('Master in something', 'Doctor in something', 'BS Something')),
       [1] => Array('talent_id' => '2', ...) )

自从我开始实习以来,Stack Overflow 对我帮助很大.我要感谢你们所有人.

Stack Overflow has been a great help for me since the start of my internship. And I want to thank all of you for that.

推荐答案

首先,您选择自己的才能(由他们的 id 索引)和您的教育.在这里,我会认为你只做了 2 个查询.那么

First, you select your talents (indexed by their id) and your education. Here, I'll consider you just did 2 queries. Then

foreach ($educations as $education) {
  $talents[$talent_id]['course'][] = $education;
}

您也可以通过 LEFT JOIN 来完成,但是当您有多个级别时,这种补水会很快变得混乱,我不推荐这样做.

You can also do it from a LEFT JOIN, but this kind of hydratation gets messy really quickly when you have multiple levels, and I wouldn't recommend it.

这篇关于PHP/MySQL - 将两个表组合成一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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