Publi

Cómo encontrar la ruta de un elemento dentro de una jerarquía en PHP

Hace poco, hablábamos de cómo generar un array que contuviera una jerarquía de elementos, vimos cómo podíamos generarlo de forma muy rápida una vez tenemos todos los elementos en una lista en la que previamente indicamos el padre de cada uno de ellos.

El problema hoy es algo distinto, tenemos esa jerarquía o árbol, y queremos encontrar la ruta hacia arriba, es decir, todos los elementos por los que tenemos que pasar para llegar hasta un elemento dado. Puede ser útil cuando estén visitando nuestra página y accedan a algún elemento interior tras el cual queremos mostrar unas migas de pan o breadcrumbs (para ello tenemos que saber todo lo que hay por encima de la categoría actual).

Como ejemplo, vamos a hacer una jerarquía con paises / comunidades autónomas / provincias / ciudades y vamos a buscar una ciudad dentro de ese array (está simplificado en el ejemplo).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php

$ex = array(
        array('id' => 1,
          'nombre' => 'España',
          'parentId' => 0),
        array('id' => 2,
          'nombre' => 'Portugal',
          'parentId' => 0),
        array('id' => 3,
          'nombre' => 'Francia',
          'parentId' => 0),
        array('id' => 4,
          'nombre' => 'Andalucía',
          'parentId' => 1),
        array('id' => 5,
          'nombre' => 'Galicia',
          'parentId' => 1),
        array('id' => 6,
          'nombre' => 'Madrid',
          'parentId' => 1),
        array('id' => 7,
          'nombre' => 'Castilla la Mancha',
          'parentId' => 1),
        array('id' => 8,
          'nombre' => 'Castilla y León',
          'parentId' => 1),
        array('id' => 9,
          'nombre' => 'Jaén',
          'parentId' => 4),
        array('id' => 10,
          'nombre' => 'Córdoba',
          'parentId' => 4),
        array('id' => 11,
          'nombre' => 'Sevilla',
          'parentId' => 4),
        array('id' => 12,
          'nombre' => 'Huelva',
          'parentId' => 4),
        array('id' => 13,
          'nombre' => 'Cádiz',
          'parentId' => 4),
        array('id' => 14,
          'nombre' => 'Málaga',
          'parentId' => 4),
        array('id' => 15,
          'nombre' => 'Granada',
          'parentId' => 4),
        array('id' => 16,
          'nombre' => 'Almería',
          'parentId' => 4),
        array('id' => 17,
          'nombre' => 'Linares',
          'parentId' => 9),
        array('id' => 18,
          'nombre' => 'Úbeda',
          'parentId' => 9),
        array('id' => 19,
          'nombre' => 'Baeza',
          'parentId' => 9),
        array('id' => 20,
          'nombre' => 'Baños de la Encina',
          'parentId' => 9),
        );

function buildTree($data, $rootId=0)
{
  $tree = array('children' => array(),
        'root' => array()
        );
  foreach ($data as $ndx=>$node)
    {
      $id = $node['id'];
      /* Puede que exista el children creado si los hijos entran antes que el padre */
      $node['children'] = (isset($tree['children'][$id]))?$tree['children'][$id]['children']:array();
      $tree['children'][$id] = $node;

      if ($node['parentId'] == $rootId)
    $tree['root'][$id] = &$tree['children'][$id];
      else
    {
      $tree['children'][$node['parentId']]['children'][$id] = &$tree['children'][$id];
    }

    }
  return $tree;
}

function findPath($tree, $childId, $reverse=true)
{
  $path = array($childId);
  $current = $childId;

  while (isset($tree['children'][$current]))
    {
      $current = $tree['children'][$current]['parentId'];
      $path[] = $current;
    }

  if (!$reverse)
    return array_reverse($path);
  else
    return $path;
}

$arbol = buildTree($ex);

print_r(findPath($arbol, 17));

Ahora buscamos el elemento con id 17 (Linares), tras ello, el script debe devolver:

Array
(
[0] => 17
[1] => 9
[2] => 4
[3] => 1
[4] => 0
)

lo cual es la ruta desde Linares hacia atrás: Linares (17), Jaén (9), Andalucía (4), España (1), root (0).

Esta función findPath() ahora mismo, funciona sólo con colecciones creadas con buildTree(), por lo que es muy importante que se respeten los nombres de los elementos (id de elemento, parentId para el id del elemento superior). De todas formas, podéis modificar estos algoritmos y os agradecería que comentaseis vuestros resultados.

Foto: Roberto Verzo (Flickr CC-by)

También podría interesarte....

There are 77 comments left Ir a comentario

  1. Pingback: Cómo encontrar la ruta de un elemento dentro de una jerarquía en PHP | PlanetaLibre /

  2. Aiden Aiden1 /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    Stick to the fantastic job, That i look over couple articles or blog posts on this subject web-site together with It is my opinion that online webpage is certainly legitimate appealing and features have communities for superb material. บาคาร่า ไม่ผ่านเอเย่นต์

  3. mahmishal mishal /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    It’s a superior strategies notably to help you the a newcomer to blogosphere, summary and even legitimate information… Bless you designed for writing this town. Required browse guide. USCIS Certified Translation Services

  4. Aiden Aiden1 /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    When i stunned while using the research people meant to makes unique post awesome. Superb pastime! ทดลองเล่นสล็อต

  5. mahmishal mishal /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    I enjoyed reading this post such an interesting info post. Thanks for providing good info. разговорный английский

  6. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    the nation’s certainly fabulous web log. the nation’s realy informative together with a a great decent project. i want it. คาสิโน888

  7. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    May very well just launched some blog page, the knowledge most people furnish on this internet site seems to have made it easier everybody vastly. Thanks a lot for the purpose of your personal instance & give good results. franchise opportunities

  8. mahmishal mishal /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    Short Bio: Best Color Prediction Game Based platforms promise to earn money quickly by allowing users to place bets and win good returns for predicting the right color. color prediction online

  9. mahmishal mishal /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    Explore a world of mind bending Trippy art, unique decor, and immersive experiences Discover captivating designs that ignite your senses and redefine creativity Sleeping goddess

  10. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    Definitely stable, brilliant, fact-filled facts in this article. Ones threads Do not sadden, and this absolutely is true in this article likewise. People generally produce a motivating understand. Would you say to Now i am fascinated?: )#) Sustain the great articles or blog posts.

  11. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    I’m motivated with all the surpassing and also preachy record which you supply in such tiny timing. 스포츠토토

  12. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 118.0.0.0 en Windows Windows NT

    Appreciate it with the write-up in addition to good points.. possibly When i likewise imagine that working hard is usually an important area of having achievements. 메이저카지노

  13. 인터넷바카라 /
    Usando Google Chrome Google Chrome 118.0.0.0 en Windows Windows NT

    Thanks so much for the post.Much thanks again. Much obliged. https://cnn714.com

  14. xmarti /
    Usando Google Chrome Google Chrome 118.0.0.0 en Windows Windows NT

    Interesting post. I Have Been wondering about this issue, so thanks for posting. Pretty cool post.It ‘s really very nice and Useful post.Thanks quad bike rental dubai

  15. xmarti /
    Usando Google Chrome Google Chrome 118.0.0.0 en Windows Windows NT

    I’ve been searching for some decent stuff on the subject and haven’t had any luck up until this point, You just got a new biggest fan!.. buggy rental dubai

  16. xmarti /
    Usando Google Chrome Google Chrome 118.0.0.0 en Windows Windows NT

    Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post with people.. hot air balloon dubai

  17. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 118.0.0.0 en Windows Windows NT

    This particular is a superb publish We observed because of reveal this. It really is exactly what I needed to determine wish within long term you’ll carry on with regard to discussing this type of superb publish. 線上輪盤

  18. Abicor Binzel /
    Usando Google Chrome Google Chrome 118.0.0.0 en Windows Windows NT

    Purchaser com pk is Pakistan first digital B2B B2C Platform dedicated to industrial item supplies We aim to provide genuine branded products with the help of authorized dealer. Abicor Binzel

  19. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 118.0.0.0 en Windows Windows NT

    I’m empowered together with the surpassing plus preachy detailing for you to decorate such minimal timing. Winter Park personal trainer

  20. 툰코 /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    This post is good enough to make somebody understand this amazing thing, and I’m sure everyone will appreciate this interesting things 툰코

  21. 툰코 /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    Thanks, that was a really cool read 툰코

  22. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    this really is great and also meanful. this really is great website. Relating is quite beneficial factor. you might have actually aided a lot of people which check out website and offer these usefull details. ajax alarmsysteem

  23. ตลาดลูกหนัง /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    sports newspaper Its many uses can be defined as follows: Sports news: Sports newspapers. It is a searched news source and reports on sports events happening around the world. ตลาดลูกหนัง With comprehensive and up-to-date information Athletes and those interested in sports can follow news about competitions, competition results, and sports promotion. and other stories immediately

  24. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    I am truly pleased to discover this website as well as do appreciate reading through helpful content articles submitted right here. The actual suggestions from the writer had been amazing, many thanks for that reveal. 토토사이트 추천

  25. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    Sustain the nice do the job, When i understand several threads within this web page in addition to I’m sure that a world-wide-web blog site is usually authentic useful possesses bought communities connected with excellent facts. manyxtoys sex toys

  26. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    Being a Novice, I will be once and for all checking out on the web regarding posts which can be regarding assist with myself. Many thanks. Practical Pie

  27. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    That is a good write-up When i viewed on account of write about the item. Really it is what exactly I need to to discover trust with foreseeable future you might go on intended for giving a really fantastic write-up. Medical Office Administration Diploma

  28. globus transfer /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    Establish forums, advisory boards, or feedback mechanisms that allow users to voice concerns, propose ethical enhancements, globus transfer and contribute to the ethical evolution of large file transfer platforms.

  29. ghori /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    aaaaa

  30. mehmood alam /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    aaaa

  31. faisal /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    I admired various information and reviews.
    alphaslot777

  32. 토토사이트 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    «You’ll Never Get Hired if You Say This in a Job Interview»
    토토사이트추천

  33. faisal /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    I admired various information and reviews.
    https://alphaslot777-gacor.com

  34. Jogo do Bicho /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    While the thrill of online gaming is undeniable, players must be aware of the legal landscape surrounding «Jogo do Bicho.» Understanding the risks and taking necessary precautions are crucial for a safe and enjoyable experience.

  35. 토토사이트 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    «The Worst Thing You Can Do? Be Positive»
    토토사이트

  36. isl turbo rebuilt /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Upgrade your machinery with Industry Diesel & Turbo’s expertise! Whether it’s Cummins ISX, ISL, or Holset, we deliver unmatched turbo rebuild and replacement services. Find the ideal turbo for your heavy-duty trucks, buses, and construction equipment.»

  37. ghori92 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Im no expert, but I believe you just made an excellent point. You certainly fully understand what youre speaking about, and I can truly get behind that. cổng game fa88

  38. faisal /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    dcwd

  39. mehmood alam /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    At JC’s Hot Bagels, family is our secret ingredient. Since 1995, our bagels have been made with love, dedication, and a touch of sibling magic. Join us in celebrating 28 years of family and flavor. bakery near me now open

  40. 홈타이 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    I have browsed most of your posts. This post is probably where I got the most 홈타이

  41. 사설토토 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    «When you read these 19 shocking food facts, you’ll never want to eat again»
    토토모음

  42. ghori92 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Most of the time I don’t make comments on websites, but I’d like to say that this article really forced me to do so. Really nice post! https://lightinfitness.com/

  43. 사설토토 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    «We Need to Talk About AI. It’s a Game Changer»
    먹튀커뮤니티

  44. 사설토토 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    «If You Spot A Woman Wearing A Ring On Her Pinky Finger, This Is What It Means»
    메이저사이트

  45. 사설토토 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    «If You Spot A Woman Wearing A Ring On Her Pinky Finger, This Is What It Means»
    메이저사이트

  46. ghori92 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Discover the enchanting world of Psilocybe Cubensis in Australia with our Golden Teacher spores. Effortlessly grow your own magic with our Psilocybe Cubensis grow kits, expertly crafted for the Aussie climate. Elevate your journey with our premium magic mushroom kits discreetly shipped across Australia. mushroom spores australia

  47. MUZAMMIL SEO MUZAMMIL SEO /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Your work is very good and I appreciate you and hopping for some more informative posts. Thank you for sharing great information to us. thiên đường trò chơi

  48. 사설토토 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    «27 Reasons Why Celebrities Love This Product»
    사설토토

  49. james alot /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Any time i actually turned against your web-site while having special particular attention without difficulty a small amount of touch submits. Gratifying way of duration, Soon we will be book-marking at this point currently have styles execute springs perfect right up. 먹튀폴리스

  50. seooo servicesss /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    I really like your take on the issue. I now have a clear idea on what this matter is all about.. Structured Network Cabling Services

  51. james alot /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Nicely We definitely liked studying it. This particular topic procured by you is extremely efficient for correct preparing. 먹튀폴리스

  52. ghori92 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Spin securely in the SafeSpin Oasis, a 2023 Toto oasis of safety. Members love the strict privacy controls, ensuring a secure environment for gaming. Join the oasis for spins that are not only exciting but also safeguarded. 안전 토토사이트

  53. 먹튀검증업체 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Quickly this particular excellent website will definitely irrefutably continually be famous among the majority of composing the weblog women and men, simply because persistent content material in addition to recommendations.

  54. 조선의밤 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    I’m just excited your offer. It is brilliant to discover the majority explain in words away from your mindset along with skill for this important issue vicinity are actually adequately determined.

  55. 먹튀검증업체 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    The heart of your writing whilst appearing agreeable in the beginning, did not sit perfectly with me after some time. Someplace throughout the paragraphs you actually were able to make me a believer but just for a while. I still have got a problem with your leaps in assumptions and you would do well to fill in all those gaps. When you actually can accomplish that, I would surely end up being fascinated.

  56. 먹튀검증업체 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    I really love the way information is presented in your post. I have added you in my social bookmark. Cheers.

  57. 뉴토끼 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    As a web site owner I believe the material here is reallymagnificent. I appreciate it for your time. You should keep it up forever! Excellent Luck.

  58. 먹튀검증업체 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    I spend time many of the subject material, I have to express i actually prized, I actually wants more information about the following, just because this can be very superb., Thanks a ton pertaining to discovering.

  59. 온라인카지노 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work 온라인카지노

  60. 메이저사이트 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have 메이저사이트

  61. 토토사이트추천 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant 토토사이트추천

  62. 우리카지노 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming 우리카지노

  63. seooo servicesss /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Immerse yourself in the ancient art of Dao Massage at Gangnam’s TOP4, endorsed by the Korean Massage Association. This traditional therapy focuses on balancing energies and promoting harmony within. Experience skilled practitioners guiding you towards a state of profound relaxation and inner peace. 강남안마 가이드

  64. seooo servicesss /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Plan your perfect wellness day with Gangnam’s top massage recommendations. Tailored to suit your health goals, our guide guarantees a soothing experience. Prioritize your well-being by reserving your spot early. 오뚝이안마

  65. 먹튀검증 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    I simply want to tell you that I am new to weblog and definitely liked this blog site. Very likely I’m going to bookmark your blog. You absolutely have wonderful stories. Cheers for sharing with us your blog 먹튀검증

  66. 슬롯사이트 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Thank you for any other informative site. The place else could I am getting that kind of information written in such a perfect approach? I have a mission that I’m just now running on, and I have been on the look out for such info 슬롯사이트

  67. MUZAMMIL SEO MUZAMMIL SEO /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    This is very educational content and written well for a change. It’s nice to see that some people still understand how to write a quality post.! vnxo88.com

  68. 카지노 커뮤니티 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Thank you for the update, very nice site 카지노 커뮤니티

  69. 먹튀검증 /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    This article was written by a real thinking writer.I agree many of the with the solid points made by the writer. 먹튀검증

  70. sdgfgf /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. There tend to be not many people who can certainly write not so simple posts that artistically. Continue the nice writing Download PC Games

  71. seooo servicesss /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Elevate your living space with beautiful, affordable kitchens from TopkwaliteitKeukenpunt. We believe a kitchen is the heart of your home and strive to make it reflect your personality seamlessly. From the initial sketch to the final design, our personal approach ensures we exceed your expectations at every stage. Keukenzaak Leeuwarden

  72. ALEXENDER RAVI /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Great knowledge, do anyone mind merely reference back to it metal roof supplier

  73. MUZAMMIL SEO MUZAMMIL SEO /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Matchfinder – your affordable path to matrimonial bliss! Browse through profiles of Indian brides and grooms from 2000 communities. Our 100 Rs memberships make matchmaking cost-effective. Enjoy the added perks of daily & weekly match alerts, enhanced search, and secure single-page registration. Trust Matchfinder for a seamless and secure matrimony experience! marriage websites

  74. ghori92 /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    Elevate your wardrobe essentials with our women’s underwear, where luxurious comfort meets chic design. buy sexy lingerie

  75. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    Experience everyday luxury with our women’s underwear, designed to fit beautifully and feel incredible. lingerie

  76. ghori92 /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    Our women’s underwear collection brings a touch of elegance to your intimates, ensuring both comfort and confidence. sexy underwear

  77. yitzchak kerrigan /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    Redefine your daily comfort with our women’s underwear, a perfect harmony of softness and support. bra store beirut

Leave a Reply