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)
Pingback: Cómo encontrar la ruta de un elemento dentro de una jerarquía en PHP | PlanetaLibre /
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. บาคาร่า ไม่ผ่านเอเย่นต์
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
When i stunned while using the research people meant to makes unique post awesome. Superb pastime! ทดลองเล่นสล็อต
I enjoyed reading this post such an interesting info post. Thanks for providing good info. разговорный английский
the nation’s certainly fabulous web log. the nation’s realy informative together with a a great decent project. i want it. คาสิโน888
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
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
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
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.
I’m motivated with all the surpassing and also preachy record which you supply in such tiny timing. 스포츠토토
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. 메이저카지노
Thanks so much for the post.Much thanks again. Much obliged. https://cnn714.com
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
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
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
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. 線上輪盤
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
I’m empowered together with the surpassing plus preachy detailing for you to decorate such minimal timing. Winter Park personal trainer
This post is good enough to make somebody understand this amazing thing, and I’m sure everyone will appreciate this interesting things 툰코
Thanks, that was a really cool read 툰코
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
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
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. 토토사이트 추천
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
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
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
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.
aaaaa
aaaa
I admired various information and reviews.
alphaslot777
«You’ll Never Get Hired if You Say This in a Job Interview»
토토사이트추천
I admired various information and reviews.
https://alphaslot777-gacor.com
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.
«The Worst Thing You Can Do? Be Positive»
토토사이트
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.»
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
dcwd
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
I have browsed most of your posts. This post is probably where I got the most 홈타이
«When you read these 19 shocking food facts, you’ll never want to eat again»
토토모음
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/
«We Need to Talk About AI. It’s a Game Changer»
먹튀커뮤니티
«If You Spot A Woman Wearing A Ring On Her Pinky Finger, This Is What It Means»
메이저사이트
«If You Spot A Woman Wearing A Ring On Her Pinky Finger, This Is What It Means»
메이저사이트
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
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
«27 Reasons Why Celebrities Love This Product»
사설토토
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. 먹튀폴리스
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
Nicely We definitely liked studying it. This particular topic procured by you is extremely efficient for correct preparing. 먹튀폴리스
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. 안전 토토사이트
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.
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.
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.
I really love the way information is presented in your post. I have added you in my social bookmark. Cheers.
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.
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.
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 온라인카지노
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 메이저사이트
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 토토사이트추천
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 우리카지노
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. 강남안마 가이드
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. 오뚝이안마
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 먹튀검증
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 슬롯사이트
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
Thank you for the update, very nice site 카지노 커뮤니티
This article was written by a real thinking writer.I agree many of the with the solid points made by the writer. 먹튀검증
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
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
Great knowledge, do anyone mind merely reference back to it metal roof supplier
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
Elevate your wardrobe essentials with our women’s underwear, where luxurious comfort meets chic design. buy sexy lingerie
Experience everyday luxury with our women’s underwear, designed to fit beautifully and feel incredible. lingerie
Our women’s underwear collection brings a touch of elegance to your intimates, ensuring both comfort and confidence. sexy underwear
Redefine your daily comfort with our women’s underwear, a perfect harmony of softness and support. bra store beirut
В салоне могут свободно поместиться до 8 человек. При необходимости будут предостав부천출장샵лены детские кресла.
Word connections isn’t just a solitary pursuit; it thrives on community engagement and collaboration. Players can compete against friends, join online tournaments, or participate in cooperative challenges where collective brainstorming leads to new discoveries.
I am genuinely thankful to the holder of this web pageraph at at this place daftar slot777
I recently had the opportunity to delve into your latest publication, and I must say, I was thoroughly captivated. The depth of your investigation and the clarity with which you present your arguments are truly commendable. Your ability to interlace various concepts into a seamless and engaging story is extraordinary. It has opened up new perspectives for me on the topic, thanks to your profound analysis. Your work greatly contributes to the ongoing conversation, and I eagerly anticipate your future writings.토토커뮤니티
it was a wonderful chance to visit this kind of site and I am happy to know. thank you so much for giving us a chance to have this opportunity.. sindrome di Di George
I recently had the pleasure of reading your latest article, and I must say, it was truly captivating. The depth of research and the clarity with which you presented your arguments were outstanding. You have a remarkable talent for blending various concepts into a seamless and engaging story, which not only held my attention but also enlightened me on the topic. The insights you provided were thought-provoking, adding valuable depth to the conversation. I eagerly anticipate your future works.입플
A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. 66 ez
Your latest article was a delight to read. I was struck by the meticulous research and the lucidity with which you’ve articulated complex ideas. The way you blend different strands of thought into a compelling narrative is exceptional. Your analysis offered me new insights, broadening my understanding of the subject. Your contribution is a valuable addition to the field, and I’m keenly looking forward to your upcoming works.토토커뮤니티
Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me. TDTC
I was reading some of your content on this website and I conceive this internet site is really informative ! Keep on putting up.
I was reading some of your content on this website and I conceive this internet site is really informative ! Keep on putting up. Peso Pluma
Great article Lot’s of information to Read…Great Man Keep Posting and update to People..Thanks poki games
Your latest article was a delight to read. I was struck by the meticulous research and the lucidity with which you’ve articulated complex ideas. The way you blend different strands of thought into a compelling narrative is exceptional. Your analysis offered me new insights, broadening my understanding of the subject. Your contribution is a valuable addition to the field, and I’m keenly looking forward to your upcoming works.토토커뮤니티
I just finished going through your most recent article, and I’m genuinely impressed. The extensive research and clear articulation of your points made it an absorbing read. Your skill in weaving together diverse ideas into a coherent and interesting narrative is remarkable. It provided me with fresh insights into the subject, thanks to your insightful examination. Your contribution significantly enriches the discourse, and I’m looking forward to your next pieces.토토커뮤니티
Great article! That kind of information is shared on the internet. Come and consult with my website. Thank you. 토토사이트
I found this blog. For what you have suggested to us, I have found some new data in your post, all things considered. The cerebrum is incredibly satisfying and I am all thanks to the astonishing degree of your article. 바카라사이트
Great article! That kind of information is shared on the internet. Come and consult with my website. Thank you. 카지노사이트
I found this blog. For what you have suggested to us, I have found some new data in your post, all things considered. The cerebrum is incredibly satisfying and I am all thanks to the astonishing degree of your article. 안전놀이터
Thank you for this fascinating post, I am happy I observed this website on Google. Not just content, in fact, the whole site is fantastic. 스포츠토토
This is a very fantastic place. It’s amazing how so many creative writings there are. It’s amazing how you got here. I’ll stop by when I have time. It was nice to meet you 안전놀이터 추천
Thank you very much for sharing such a useful article. Will definitely saved and revisit your site. 파워볼사이트 추천
“That’s why marketing and advertising that you simply applicable exploration previous to publishing. It will be easy to write down superior write-up that way. 토토사이트 추천
This article is massive increase in knowledge and more then that it is useful and interesting too, keep posting more. 토토사이트
Excellent article. The writing style which you have used in this article is very good and it made the article of better quality. 온라인카지노사이트
I am happy to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. Thanks errordomain=nscocoaerrordomain&errormessage=could not find the specified shortcut.&errorcode=4
Wonderful blog! Do you have any tips and hints for aspiring writers? Because I’m going to start my website soon, but I’m a little lost on everything. Many thanks! https://188.166.232.208/
In New York, there are various personal security services available to individuals seeking protection for themselves, their families, or their properties. These services can range from unarmed security guards to highly trained executive protection specialists. Here are some options for personal security services in New York:Private Security New York
This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post. ae888.city
Hey, this day is too much good for me, since this time I am reading this enormous informative article here at my home. Thanks a lot for massive hard work. 68.183.190.172
Say hello to firmer, younger-looking skin with Ultherapy®! FDA-approved and non-surgical, it’s the ultimate solution for facial rejuvenation. Using microfocused ultrasound technology, it stimulates collagen production for deep skin regeneration and a lifting effect that lasts up to 2 years. Experience smoother, toned skin without scalpels or needles, thanks to Ultherapy®’s precise ultrasound guidance. Centri autorizzati Ultherapy Milano
The 1xBet promo code is «GIFT888». With this code, you can be sure you’re getting the best possible welcome bonus 100% up to 130$. 1xBet is an online gambling company licensed under the Curaçao eGaming license. 1xBet bonus code is required to claim any of the sportsbook’s current welcome offers in legal. 1x bet free promo code
Your blog has piqued a lot of real interest. I can see why since you have done such a good job of making it interesting. I appreciate your efforts very much. roof consultation
When conventional methods fail, egg donation offers a new path to parenthood. At Next Fertility GynePro, we understand the complexities of fertility struggles and provide tailored solutions to fit your needs. Explore our advanced techniques and supportive care. dove si fa ovodonazione in italia
Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! 드라마 다시보기
I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. 안전놀이터