简体   繁体   中英

PHP + mySQL recursive select to create hierarchy menu

I am learning PHP and mySQL, and need some help to create some code to build a hierarchy menu base on parent child elements. deep level will be 1 child.

This is the table structure:

CREATE TABLE `businessprocess` (`bp_id` int(11), `bp_order` int(11), `bp_name` varchar(50), `bp_parent` int(11), `bp_active` tinyint(1), `dp_id` int(11)) ENGINE=InnoDB;

This the data:

INSERT INTO `businessprocess` (`bp_id`, `bp_order`, `bp_name`, `bp_parent`, `bp_active`, `dp_id`) VALUES
(1, 1000, 'Solicitud de Servicios (fijo y movil)', NULL, 1, 1),
(2, 1100, 'Personas', 1, 1, 1),
(3, 1200, 'Empresas', 1, 1, 1),
(4, 2000, 'Baja de Servicio', NULL, 1, 1),
(5, 2100, 'Personas', 4, 1, 1),
(6, 2200, 'Empresas', 4, 1, 1),
(7, 2300, 'Defunción', 4, 1, 1),
(8, 2400, 'Tercero', 4, 1, 1),
(9, 3000, 'Modificacion de Servicio', NULL, 1, 1),
(10, 4000, 'Recambio de Equipo', NULL, 1, 1),
(11, 3100, 'Personas o Empresas', 9, 1, 1),
(12, 3200, 'Tercero', 9, 1, 1),
(13, 4100, 'Personas o Empresas', 10, 1, 1),
(14, 4200, 'Tercero', 10, 1, 1);

This is the output needed for menu in PHP:

    Solicitud de Servicios (fijo y movil)
    --Personas
    --Empresas
    Baja de Servicio
    --Personas
    --Empresas
    --Defunción
    --Tercero
    Modificacion de Servicio
    --Personas o Empresas
    --Tercero
    Recambio de Equipo
    --Personas o Empresas
    --Tercero

any help is really appreciated. Thanks! AC

First run

 SELECT bp_id, `bp_name` FROM `businessprocess` WHERE bp_parent IS NULL

Second for each of the returned result run

SELECT `bp_name` FROM `businessprocess` WHERE bp_parent IS NOT NULL  AND `bp_parent` = bp_id(gotten from the previous result)

It should display what you need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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