Недавно, возникла потребность сделать древовидный, порядковый список категорий, в одном из проектов. 2 главных условия, которые соблюдал: 1) в html должны наглядно показываться родительские элементы и их "дети"; 2) для всей операции 1 SQL запрос. SQL-структура была такая:
  1. ---------------------------------------------------------------------------------
  2. | FIELD          | Type             | NULL   | KEY | DEFAULT   | Extra
  3.  ---------------------------------------------------------------------------------
  4. | categoryID     | int(3)           | NO    | PRI   | NULL     | AUTO_INCREMENT  |
  5. | parent         | int(3)           | NO    |       | 0        |                 |
  6. | name           | varchar(255)     | NO    |       | NULL     |                 |
  7. | slug           | varchar(255)     | NO    |       | NULL     |                 |
  8. | pic            | varchar(255)     | YES   |       | NULL     |                 |
  9.  ---------------------------------------------------------------------------------
  10. 5 rows IN SET (0.03 sec)
После запроса в БД массив получился такой.
  1. Array
  2. (
  3.     [0] => Array
  4.         (
  5.             [categoryID] => 1
  6.             [parent] => 0
  7.             [name] => Фильмы
  8.             [slug] => films
  9.             [pic] =>
  10.         )
  11.  
  12.     [1] => Array
  13.         (
  14.             [categoryID] => 2
  15.             [parent] => 0
  16.             [name] => Музыка
  17.             [slug] => music
  18.             [pic] =>
  19.         )
  20. [...]
  21. )
Для удобной работы я сгруппировал массив по categoryID, заменив его ключи на этот идентификатор.
  1. foreach ($data AS $v)
  2. $array[$v['categoryID']] = $v;
А вот и сама функция, которая пишет в глобальный массив $g_data результат своей рекурсивной работы.
  1. FUNCTION tree (&$data, $node_id, $lvl = 0)
  2. {
  3.    switch ($lvl)
  4.    {
  5.       // для каждой категории может быть действие (напр. присвоить id)
  6.         case 0:
  7.         $html = '<option style="font-weight:bolder;" disabled>- КОРЕНЬ -</strong>'."\n";
  8.         break;
  9.         DEFAULT:
  10.         /* str_repeat делает отступ слева, в зависимости от уровня кат-ии. Это наглядно показывает юзеру родителя категории и его дочерний элемент. А если кат-я самая "верхняя", она выделяется стилем font-weight:bold */
  11.         $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";
  12.     }
  13.   $this->g_data['tree'] .= $html;
  14.        
  15.    // рекурсия
  16.    foreach ($data AS $row)
  17.       IF ($row['parent'] == $node_id)
  18.          $this->tree($data, $row['categoryID'], $lvl   1);
  19. }
Остаётся только запустить процесс.
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


Войдите или зарегистрируйтесь, чтобы написать комментарий.