简体   繁体   English

MySQL查询需要帮助-按父组

[英]mysql query help needed - Group by parent

I'm trying to do a mysql query that will create an array of parent items, with their child items underneath. 我正在尝试执行一个mysql查询,该查询将创建一个父项数组,其子项位于下面。 But I'm not 100% sure how. 但我不确定100%如何。 Here's what I have done so far: 到目前为止,这是我所做的:

SELECT * FROM categories as rf ORDER BY parent, name ASC SELECT * FROM类别作为rf ORDER BY父项,名称为ASC

And here's what is being outputted (array): 这是输出的内容(数组):

Array
(
    [0] => stdClass Object
        (
            [id] => 7
            [name] => Safety Clothing
            [parent] => 0
        )

    [1] => stdClass Object
        (
            [id] => 8
            [name] => Safety Footwear
            [parent] => 0
        )

    [2] => stdClass Object
        (
            [id] => 9
            [name] => Workwear
            [parent] => 0
        )

    [3] => stdClass Object
        (
            [id] => 4
            [name] => Polos
            [parent] => 7
        )

    [4] => stdClass Object
        (
            [id] => 3
            [name] => Shirts
            [parent] => 7
        )

    [5] => stdClass Object
        (
            [id] => 6
            [name] => Jackets
            [parent] => 9
        )

    [6] => stdClass Object
        (
            [id] => 1
            [name] => Pants
            [parent] => 9
        )

    [7] => stdClass Object
        (
            [id] => 2
            [name] => Shirts
            [parent] => 9
        )

    [8] => stdClass Object
        (
            [id] => 5
            [name] => Shorts
            [parent] => 9
        )

)

As you can see the child items have the id of the parent items (parent is set to 0), but I'm not sure how to merge it all together to do an array something like this: 如您所见,子项具有父项的ID(父项的ID设置为0),但是我不确定如何将所有子项合并在一起以形成如下数组:

parent 父母

-- child -孩子

-- child -孩子

parent 父母

parent 父母

-- child -孩子

-- child -孩子

-- child -孩子

Any help would be appreciated :) 任何帮助,将不胜感激 :)

Also

SELECT parent,GROUP_CONCAT(name) as names FROM categories as rf GROUP BY 1; SELECT parent,GROUP_CONCAT(name)作为类别的名称,如rf GROUP BY 1;

You will get one row for every parent with parent id in the first column and child names separated by comma on the second column. 您将在第一列中为每个具有父ID的父对象获得一行,在第二列中以逗号分隔子名称。

If it is possible to build nested arrays using the data from that array: Each object would have an Array variable. 如果可以使用该数组中的数据构建嵌套数组,则:每个对象将具有一个Array变量。 Then after the initial array is built, move the children under their parent manually by parsing the initial array. 然后,在构建初始数组之后,通过解析初始数组将子级手动移到其父级下。

The method that parses would be recursive, and would take the initial array and the child array it is currently building. 解析的方法将是递归的,并将采用初始数组和当前正在构建的子数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM