Link to home
Create AccountLog in
Avatar of Eddie Shipman
Eddie ShipmanFlag for United States of America

asked on

PHP parent/child categories

Have the data below in a table:

    programgroup,programcode
    "C1","AM"
    "C1","CC"
    "C1","CC"
    "C1","CC"
    "C1","CC"
    "C1","CC"
    "C1","CC"
    "C1","CP"
    "C1","CP"
    "C1","CP"
    "C1","CP"
    "C1","PL"
    "C1","PL"
    "C1","PL"
    "C1","PL"
    "C1","PL"
    "C4","2IC"
    "C4","2IC"
    "C4","2IC"
    "C4","2IC"
    "C4","2IC"
    "C4","AO"
    "C4","AO"
    "C4","AO"
    "C4","IP"
    "C4","IP"
    "C4","PA"
    "C4","PA"
    "C4","PM"
    "C4","PR"
    "C4","PR"
    "C4","SR"
    "C4","WH3"

Open in new window


I'm reading the data and iterating over the records and  I need to insert a category in another table for each ProgramGroup and a child category for each ProgramCode that has a parent_id of the category for the ProgramGroup it is contained in,

Sample output: (MAIN category will already exist)

    category_id, value, parent_id
    0,  "MAIN", null
    1,  "C1",  0
    2,  "AM",  1
    3,  "CC",  1
    4,  "CP",  1
    5,  "PL",  1
    6,  "C4",  0
    7,  "21C", 6
    8,  "AO",  6
    9,  "IP",  6
    10, "PA",  6
    11, "PM",  6
    12, "PR",  6
    13, "SR",  6
    14, "WH3", 6

Open in new window

   

Can anyone tell me how to do this in PHP pseudo code?
ASKER CERTIFIED SOLUTION
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Bear in mind that approach will only work for a hierarchy that's a simple 2-level parent/child structure. If you need a more recursive/dynamic hierarchy, it's better to build out a tree structure using PHP objects and build everything using recursive methods. It's more complicated, but more flexible.

I also made some assumptions about table names and that the category_id in the new table is an auto-incrementing primary key.
Avatar of Eddie Shipman

ASKER

Since I only asked for pseudo-code, while not perfect for my situation, it led me to the solution. Thanks.