Jump to content


Photo

Sorting through Multi-Dimensional Array


  • Please log in to reply
1 reply to this topic

#1 pbjorge12

pbjorge12
  • Members
  • Pip
  • Newbie
  • 9 posts

Posted 13 April 2006 - 11:30 PM

I have a PHP function that recieves a file path and returns an array like below...

Array
(
   [index.php] => /usr/local/www/index.php
   [js] => Array
       (
           [async.js] => /usr/local/www/js/async.js
           [dom.js] => /usr/local/www/js/dom.js
           [effects.js] => /usr/local/www/js/effects.js
           [prototype.js] => /usr/local/www/js/prototype.js
       )

   [logo.png] => /usr/local/www/logo.png
   [server.php] => /usr/local/www/server.php
   [test.js] => /usr/local/www/test.js
) 

How do I sort through that array and return the HTML similar to below?
<ul id="fileList">
<li id="firstLevel">index.php</li>
<li id="firstLevel">js</li>
<li id="secondLevel">asnyc.js</li>
<li id="secondLevel">dom.js</li>
<li id="secondLevel">effects.js</li>
<li id="secondLevel">prototype.js</li>
<li id="firstLevel">logo.png</li>
<li id="firstLevel">server.php</li>
<li id="firstLevel">test.js</li>
</ul>

Thank you!

#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 14 April 2006 - 12:03 AM

Try

$data = array
(
   'index.php' => '/usr/local/www/index.php',
   'js' => array
       (
           'async.js' => '/usr/local/www/js/async.js',
           'dom.js' => '/usr/local/www/js/dom.js',
           'effects.js' => '/usr/local/www/js/effects.js',
           'prototype.js' => '/usr/local/www/js/prototype.js'
       ),

   'logo.png' => '/usr/local/www/logo.png',
   'server.php' => '/usr/local/www/server.php',
   'test.js' => '/usr/local/www/test.js'
);

function listArray($arr, $level=0) {
         foreach($arr as $item) {
                 if (is_array($item)) {
                     listArray($item, $level+1);
                 }
                 else {
                       $id = $level==0 ? 'firstlevel':'secondlevel';
                       echo "<li id='$id'>$item</li><br>\n";
                 }
         }
}

echo "<ul id='fileList'>\n";
listArray($data);
echo "</ul>";

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users