Page 1 of 1

How can turn multi-dimensional array into series of <ul>?

Posted: Thu Mar 31, 2011 7:14 am
by someguyhere
I have an array (see below) that I want to turn into a series of unordered lists, but can't seem to find a foreach structure that works for this situation. Any advice would be greatly appreciated.

Code: Select all

Array (
[0] => Array (
  [0] => <li>Affiliate Networks</li>
  [1] => <li>Copywriting</li>
  [2] => <li>Email Marketing</li>
) 

[1] => Array (
  [0] => <li>Graphic Design</li>
  [1] => <li>Photographers</li>
  [2] => <li>Public Relations</li>
) 

[2] => Array (
  [0] => <li>Video Production</li>
  [1] => <li>Website Design</li>
  [2] => <li>Website Hosting</li>
)
)

Re: How can turn multi-dimensional array into series of <ul>

Posted: Thu Mar 31, 2011 9:23 am
by social_experiment

Code: Select all

<?php
$me = array(
		array('Affiliate Networks', 'Copywriting', 'Email Marketing'),
		array('Graphic Design', 'Photographers', 'Public Relations'),
		array('Video Production', 'Website Design', 'Website Hosting')
);
	foreach ($me as $value) {
		if (is_array($value)) {
			echo '<ul>';
			foreach ($value as $sub_value ) {
				echo '<li>' . $sub_value . '</li>';
			}
			echo '</ul>';
		}
	}

?>
This turns the multi-dimensional array in 3 smaller lists.
Hth

Re: How can turn multi-dimensional array into series of <ul>

Posted: Thu Mar 31, 2011 9:23 am
by MindOverBody

Code: Select all

$finalOutput = "";
foreach( $array as $list ){
     $output = "<ul>";
     foreach( $list as $item ) $output .= $item;
     $output .= "</ul>";
     $finalOutput .= $output;
}
$array is your targeted array, and $finalOutput is string of unordered lists.

Cheers!

Re: How can turn multi-dimensional array into series of <ul>

Posted: Thu Mar 31, 2011 5:35 pm
by someguyhere
MindOverBody wrote:

Code: Select all

$finalOutput = "";
foreach( $array as $list ){
     $output = "<ul>";
     foreach( $list as $item ) $output .= $item;
     $output .= "</ul>";
     $finalOutput .= $output;
}
$array is your targeted array, and $finalOutput is string of unordered lists.

Cheers!
It worked perfectly, though the first line isn't needed.

Thanks!

Re: How can turn multi-dimensional array into series of <ul>

Posted: Thu Mar 31, 2011 6:16 pm
by McInfo
someguyhere wrote:It worked perfectly, though the first line isn't needed.
The first line is necessary to prevent an "undefined variable" notice on the sixth line.

A better solution might be a recursive function to handle lists of any depth.

HTML entity encoding of the list items would be prudent.