加入表数据

时间:2013-08-28 12:38:21

标签: mysql sql join

我有一张表:

id   title     type   expl   bubble_content   onfocus   req   dorder   label    mirror
1    Fullname  1      1      Your fullname    Yes       0     0        0        NULL

然后是另一张表:

id     fieldid    relid    dorder
4      1          2        0
5      1          1        0

我如何加入这两个表,结果如下:

0 => array(
     'id' => 1,
     'title' => 'Fullname',
     .... etc ....
     'relid' => 2,
     'relid' => 1),
1 => array(
     .... etc ....
))

我尝试过使用INNER JOIN / LEFT JOIN,但这会为每个relid生成两行/数组,我真的希望特定fieldid的所有数据都存在于同一个数组中,如上图所示。

1 个答案:

答案 0 :(得分:1)

您不能在阵列中拥有2个具有相同名称的键。在您的示例中,您有2' relid',第二个将覆盖第一个。

您可以对PHP进行编码,以便将这些行合并为一个:

    $output = array();
    while ($row = mysql_fetch_assoc($result))
    {
        // Capture all values for this row first.
        // If this is the new row from the first table, store.
        if (!isset($output[$row['id']]))
        {
            $output[$row['id']] = $row;

            // Make a new array for relids.
            $output[$row['id']]['relids'] = array();
        }


        $output[$row['id']]['relids'][] = $row['relid']; 

    }

您的输出数组将如下所示:

0 => array(
 'id' => 1,
 'title' => 'Fullname',
 .... etc ....
 'relids' => array(2, 1),
1 => array(
 .... etc ....
))
相关问题