PHP: Построение древовидных данных в PHP
Недавно, возникла потребность сделать древовидный, порядковый список категорий, в одном из проектов.
2 главных условия, которые соблюдал:
1) в html должны наглядно показываться родительские элементы и их "дети";
2) для всей операции 1 SQL запрос.
SQL-структура была такая:
После запроса в БД массив получился такой.
Для удобной работы я сгруппировал массив по categoryID, заменив его ключи на этот идентификатор.
А вот и сама функция, которая пишет в глобальный массив $g_data результат своей рекурсивной работы.
Остаётся только запустить процесс.
- ---------------------------------------------------------------------------------
- | FIELD | Type | NULL | KEY | DEFAULT | Extra
- ---------------------------------------------------------------------------------
- | categoryID | int(3) | NO | PRI | NULL | AUTO_INCREMENT |
- | parent | int(3) | NO | | 0 | |
- | name | varchar(255) | NO | | NULL | |
- | slug | varchar(255) | NO | | NULL | |
- | pic | varchar(255) | YES | | NULL | |
- ---------------------------------------------------------------------------------
- 5 rows IN SET (0.03 sec)
- Array
- (
- [0] => Array
- (
- [categoryID] => 1
- [parent] => 0
- [name] => Фильмы
- [slug] => films
- [pic] =>
- )
- [1] => Array
- (
- [categoryID] => 2
- [parent] => 0
- [name] => Музыка
- [slug] => music
- [pic] =>
- )
- [...]
- )
- foreach ($data AS $v)
- $array[$v['categoryID']] = $v;
- FUNCTION tree (&$data, $node_id, $lvl = 0)
- {
- switch ($lvl)
- {
- // для каждой категории может быть действие (напр. присвоить id)
- case 0:
- $html = '<option style="font-weight:bolder;" disabled>- КОРЕНЬ -</strong>'."\n";
- break;
- DEFAULT:
- /* str_repeat делает отступ слева, в зависимости от уровня кат-ии. Это наглядно показывает юзеру родителя категории и его дочерний элемент. А если кат-я самая "верхняя", она выделяется стилем font-weight:bold */
- $html = '<option '.($data[$node_id]['parent']==0?'style="font-weight:bold;':'').' value="'.$data[$node_id]['categoryID'].'">'.str_repeat(' ', $lvl) . $data[$node_id]['name'].'</option>'."\n";
- }
- $this->g_data['tree'] .= $html;
- // рекурсия
- foreach ($data AS $row)
- IF ($row['parent'] == $node_id)
- $this->tree($data, $row['categoryID'], $lvl 1);
- }
tree($array, 0);
pyncelern 01 сентября в 22:51 #
Tadalafil with once-daily OAD and on-demand pro re nata PRN dose regimens is sufficient for treating ED tadalista vs cialis
pyncelern 01 сентября в 22:51 #
Tadalafil with once-daily OAD and on-demand pro re nata PRN dose regimens is sufficient for treating ED tadalista vs cialis
Quapipt 04 сентября в 04:43 #
This drug should be stored at controlled temperatures priligy dosage
Quapipt 04 сентября в 04:43 #
This drug should be stored at controlled temperatures priligy dosage
ignomia 06 сентября в 03:30 #
DERMAFACS RecoverX Review Does This Skin Repair Cream Work buy cialis 5mg daily use Selected from data included with permission and copyrighted by First Databank, Inc
ignomia 06 сентября в 03:30 #
DERMAFACS RecoverX Review Does This Skin Repair Cream Work buy cialis 5mg daily use Selected from data included with permission and copyrighted by First Databank, Inc
Speelycle 08 сентября в 12:21 #
cialis generic 5mg Viagra, recreational use
Speelycle 08 сентября в 12:21 #
cialis generic 5mg Viagra, recreational use
Altendelf 11 сентября в 04:34 #
clomid generic name The methods used to determine hCG have changed since the studies, on which the present recommendations are based, were performed.
Altendelf 11 сентября в 04:34 #
clomid generic name The methods used to determine hCG have changed since the studies, on which the present recommendations are based, were performed.
FesUlceme 14 сентября в 10:37 #
post cycle therapy nolvadex
FesUlceme 14 сентября в 10:37 #
post cycle therapy nolvadex
amizavy 17 сентября в 19:57 #
doxycycline dosage for lyme disease Most notably, it showed selective cytotoxicity against five renal cancer cell lines 786- 0, ACHN, CAK- 1, TK- 10 and UO- 31, with a mean LC 50 of 0.
amizavy 17 сентября в 19:58 #
doxycycline dosage for lyme disease Most notably, it showed selective cytotoxicity against five renal cancer cell lines 786- 0, ACHN, CAK- 1, TK- 10 and UO- 31, with a mean LC 50 of 0.
Ninysnant 08 октября в 17:20 #
Less than 20 percent of the chemicals in personal care products have been tested for safety lasix effect on potassium Stanton rbprxzcOpTtxJLFNLC 5 20 2022
Ninysnant 08 октября в 17:20 #
Less than 20 percent of the chemicals in personal care products have been tested for safety lasix effect on potassium Stanton rbprxzcOpTtxJLFNLC 5 20 2022
invosonse 14 октября в 09:02 #
chlorpromazine increases and salmeterol decreases sedation cheap cialis from india
invosonse 14 октября в 09:02 #
chlorpromazine increases and salmeterol decreases sedation cheap cialis from india
exparma 26 октября в 15:01 #
Many survivors feel worried or anxious that the cancer will come back after treatment driponin online
exparma 26 октября в 15:01 #
Many survivors feel worried or anxious that the cancer will come back after treatment driponin online
whappeapy 07 ноября в 22:00 #
2005; Bim S 2A to target Mcl 1 but not Bcl 2, Bcl x L, Bcl w, or A1 Lee et al what is nolvadex used for
whappeapy 07 ноября в 22:00 #
2005; Bim S 2A to target Mcl 1 but not Bcl 2, Bcl x L, Bcl w, or A1 Lee et al what is nolvadex used for
uncevelon 09 ноября в 10:29 #
where can i buy priligy online safely Because ginseng does not exhibit a proliferative effect, it may play a protective role against breast cancer rather than serve as a mitogen
uncevelon 09 ноября в 10:29 #
where can i buy priligy online safely Because ginseng does not exhibit a proliferative effect, it may play a protective role against breast cancer rather than serve as a mitogen
mismJique 15 ноября в 08:23 #
how is clomid taken A liquid plasticizer can be included in the polymer blend composition in a range of greater than 0 to about 20 by weight of the polymer blend composition
mismJique 15 ноября в 08:23 #
how is clomid taken A liquid plasticizer can be included in the polymer blend composition in a range of greater than 0 to about 20 by weight of the polymer blend composition
Tumejoime 17 ноября в 17:16 #
how long does doxycycline take to work Bax, Bak, Bid, Bad, DNA, RNA, ribozymes, RNAse, siRNAs, enzymes, 111 In oxine, 59 Fe, 67 Cu, 125 I, 99 Te, 51 Cr, 32 P, 3 H, 35 S, 14 C, IFN О±, IL 2, all trans retinoic acid, EGFR, VGFR, FGFR, PDGFR, STI 571, GLEEVEC, HERCEPTIN, RITUXAN, raloxifene, tamoxifen, flutamide, bicalutamide, finasteride, aminoglutethamide, ketoconazole, corticosteroids, celecoxib, meloxicam, NS 398, irinotecan CPT 11, fludarabine, dacarbazine, dexamethasone, mitoxantrone, MYLOTARG, VP 16, 5 FU, cisplatin, carboplatin, gemcitabine, doxorubicin, TAXOTERE, TAXOL, tenofovir disoproxil fumarate, zidovudine, lamivudine, abacavir, zalcitabine, didanosine, stavudine, nevirapine, delavirdine, efavirenz, saquinavir SQV HGC, saquinavir SQV SGC, ritonavir, indinavir, nelfinavir, amprenavir, mechlorethamine, cyclophosphamide, ifosfamide, melphalan, L sarcolysin, chlorambucil, hexamethylmelamine, thiotepa, busulfan, carmustine, lomustine, semustine, streptozocin, dacarbazine, methotrexate, fluorouracil, floxuridine, cytarabine, mercaptopurine, thioguanine, pentostatin, vinblastine, vincristine, etoposide, teniposide, dactinomycin, daunorubicin, bleomycin, plicamycin, mitomycin, L asparaginase, hydroxyurea, procarbazine, mitotane, aminoglutethimide, prednisone, hydroxyprogesterone caproate, medroxyprogesterone acetate, megestrol acetate, diethylstilbestrol, ethinyl estradiol, testosterone propionate, fluoxymesterone, flutamide, and leuprolide, and combinations thereof
Tumejoime 17 ноября в 17:16 #
how long does doxycycline take to work Bax, Bak, Bid, Bad, DNA, RNA, ribozymes, RNAse, siRNAs, enzymes, 111 In oxine, 59 Fe, 67 Cu, 125 I, 99 Te, 51 Cr, 32 P, 3 H, 35 S, 14 C, IFN О±, IL 2, all trans retinoic acid, EGFR, VGFR, FGFR, PDGFR, STI 571, GLEEVEC, HERCEPTIN, RITUXAN, raloxifene, tamoxifen, flutamide, bicalutamide, finasteride, aminoglutethamide, ketoconazole, corticosteroids, celecoxib, meloxicam, NS 398, irinotecan CPT 11, fludarabine, dacarbazine, dexamethasone, mitoxantrone, MYLOTARG, VP 16, 5 FU, cisplatin, carboplatin, gemcitabine, doxorubicin, TAXOTERE, TAXOL, tenofovir disoproxil fumarate, zidovudine, lamivudine, abacavir, zalcitabine, didanosine, stavudine, nevirapine, delavirdine, efavirenz, saquinavir SQV HGC, saquinavir SQV SGC, ritonavir, indinavir, nelfinavir, amprenavir, mechlorethamine, cyclophosphamide, ifosfamide, melphalan, L sarcolysin, chlorambucil, hexamethylmelamine, thiotepa, busulfan, carmustine, lomustine, semustine, streptozocin, dacarbazine, methotrexate, fluorouracil, floxuridine, cytarabine, mercaptopurine, thioguanine, pentostatin, vinblastine, vincristine, etoposide, teniposide, dactinomycin, daunorubicin, bleomycin, plicamycin, mitomycin, L asparaginase, hydroxyurea, procarbazine, mitotane, aminoglutethimide, prednisone, hydroxyprogesterone caproate, medroxyprogesterone acetate, megestrol acetate, diethylstilbestrol, ethinyl estradiol, testosterone propionate, fluoxymesterone, flutamide, and leuprolide, and combinations thereof
floanny 18 ноября в 21:57 #
I feel great, and our plan is to move beyond the six month mark and continue traveling around Southeast Asia for the foreseeable future lasix for pulmonary edema
floanny 18 ноября в 21:57 #
I feel great, and our plan is to move beyond the six month mark and continue traveling around Southeast Asia for the foreseeable future lasix for pulmonary edema
guetkeype 19 ноября в 23:15 #
stromectol alternative This drug may rarely cause vision changes
guetkeype 19 ноября в 23:15 #
stromectol alternative This drug may rarely cause vision changes
towScoole 09 декабря в 20:22 #
where to buy finasteride With GOD anything is possible
towScoole 09 декабря в 20:22 #
where to buy finasteride With GOD anything is possible
AnattyTaK 11 декабря в 20:46 #
clomiphene moa Secondary causes see Table 1 alone may cause mild to moderate HTG; however, they frequently interact with polygenic susceptibility factors to produce an HTG phenotype
AnattyTaK 11 декабря в 20:46 #
clomiphene moa Secondary causes see Table 1 alone may cause mild to moderate HTG; however, they frequently interact with polygenic susceptibility factors to produce an HTG phenotype
Giggino 11 декабря в 23:22 #
Monitor Closely 1 alpelisib will decrease the level or effect of nateglinide by pharmacodynamic synergism buy cialis on line The increased frequency and activation status of Treg cells that we observe in Tet2 3 fl fl Foxp3 Cre mice is also commonly observed in mice with Treg perturbations, and may reflect a compensatory increase in Treg cell numbers observed under conditions of insufficient overall Treg cell function 8, 35
Giggino 11 декабря в 23:22 #
Monitor Closely 1 alpelisib will decrease the level or effect of nateglinide by pharmacodynamic synergism buy cialis on line The increased frequency and activation status of Treg cells that we observe in Tet2 3 fl fl Foxp3 Cre mice is also commonly observed in mice with Treg perturbations, and may reflect a compensatory increase in Treg cell numbers observed under conditions of insufficient overall Treg cell function 8, 35
elencebig 12 декабря в 02:52 #
griseofulvin montelukast sandoz cena People enrolled in the government food assistance programuse plastic vouchers similar to debit cards zithromax 500mg
elencebig 12 декабря в 02:52 #
griseofulvin montelukast sandoz cena People enrolled in the government food assistance programuse plastic vouchers similar to debit cards zithromax 500mg
driense 14 декабря в 05:31 #
The first LP was performed in the late 19th century by Heinrich Iraneus Quincke and Walter Essex Wynterin buy priligy on the internet without a prescription
driense 14 декабря в 05:31 #
The first LP was performed in the late 19th century by Heinrich Iraneus Quincke and Walter Essex Wynterin buy priligy on the internet without a prescription
Inackense 27 января в 16:58 #
valtrex over the counter It is content, instead, to treat babies as a commodity, to turn persons into merchandise and men and women into breeding stock and to consider all of this as acceptable because it has found nice words to describe it
Inackense 27 января в 16:58 #
valtrex over the counter It is content, instead, to treat babies as a commodity, to turn persons into merchandise and men and women into breeding stock and to consider all of this as acceptable because it has found nice words to describe it
suescinia 29 января в 02:18 #
A double blind, placebo controlled, randomized withdrawal trial of LYRICA CR in adults with fibromyalgia failed to demonstrate efficacy propecia viagra combined
suescinia 29 января в 02:18 #
A double blind, placebo controlled, randomized withdrawal trial of LYRICA CR in adults with fibromyalgia failed to demonstrate efficacy propecia viagra combined