0

i have an array , like this

Array ( [id] => 1 [did] => 1 [title] => first link [link] => link.com ) 
Array ( [did] => 1 [title] => second link [link] => link2.com ) 
Array ( [id] => 2 [did] => 2 [title] => forum 1 [link] => forum.php ) 
Array ( [did] => 2 [title] => forum 2 => viewtopic.php ) 
Array ( [did] => 2 [title] => register [link] => register.php ) 

and i want to extract it , like this

- first link
-- seconde link
- forum 1
-- forum 2
-- register

id , is main , and did , is parent in this array. any way? i want this output :

<ul>
    <li><a href="link.com">first link</a>
        <ul>
            <li><a href="link2.com">seconde link</a></li>
        </ul>
    </li>
    <li><a href="forum.php"> forum 1</a>
        <ul>
            <li><a href="viewtopic.php"> forum 2</a></li>
            <li><a href="register.php"> register</a></li>
        </ul>
    </li>
</ul>
10
  • you have this array's or you can change them? Commented Apr 16, 2015 at 10:53
  • What have you tried? Start by using a foreach loop and conditions to check child-parent relation. Commented Apr 16, 2015 at 10:53
  • How this data added to array?? What you need to do?? Is there any frame works? or peo PHP??? Commented Apr 16, 2015 at 10:56
  • this array used for menu & submenu. foreach loop , does'nt work for me , perhaps , i did it wrong. Commented Apr 16, 2015 at 10:57
  • ok but i ask to you if you can change the arrays or where you get this arrays? Commented Apr 16, 2015 at 10:59

1 Answer 1

1

The structure isn't that clean, but sometime the data doesn't come in clean. Something like this should work (although the <?= short tag may cause issues if that isn't set up in your environment). I used colons instead of braces only because I think it is easier to read in this kind of mixed code.

<ul>
<?php foreach ($arr as $item): ?>
    <li><a href="<?=$item['link']?>"><?=$item['title']?></a>
        <ul>
        <?php 
            foreach ($arr as $item2): 
               if ((array_key_exists('did', $item2) && ($item2['did'] == $item['id'])):
        ?>
             <li><a href="<?=$item2['link']?>"><?=$item2['title']?></a></li>    
        <?php
               endif;
             endforech;
        ?>
        </ul>
    </li>
<?php endforeach;?>
</ul>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.