可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have the following array set in a php script and i am trying to get it to output as per the code below. I have tried looping but i am at a loss as to how i get it to show the sub arrays. I am hoping someone can help me.
PHP Array
$fruits = array(); $fruits[] = array('type' => 'Banana', 'code' => 'ban00'); $fruits[] = array('type' => 'Grape', 'code' => 'grp01'); $fruits[] = array('type' => 'Apple', 'code' => 'apl00', array('subtype' => 'Green', 'code' => 'apl00gr'), array('subtype' => 'Red', 'code' => 'apl00r') ); $fruits[] = array('type' => 'Lemon', 'code' => 'lem00');
Desired Output
<ul> <li><input type="checkbox" name="fruit" value="Banana"> Banana</li> <li><input type="checkbox" name="fruit" value="Grape"> Grape</li> <li>Apple <ul> <li><input type="checkbox" name="fruit" value="Green"> Green</li> <li><input type="checkbox" name="fruit" value="Red"> Red</li> </ul> </li> <li><input type="checkbox" name="fruit" value="Lemon"> Lemon</li> </ul>
回答1:
You can use recursive function. Note that this is a example and not a direct solution, as we are here to learn and not to get the job done - change this as needed.
function renderList(array $data) { $html = '<ul>'; foreach ($data as $item) { $html .= '<li>'; foreach ($item as $key => $value) { if (is_array($value)) { $html .= renderList($value); } else { $html .= $value; } } $html .= '</li>'; } $html .= '</ul>'; return $html; } $data = array(); $data[] = array('A'); $data[] = array('B', array(array('C'))); $data[] = array('D'); echo renderList($data);
The output of this will be:
Or in html form:
<ul> <li>A</li> <li>B <ul> <li>C</li> </ul> </li> <li>D</li> </ul>
回答2:
You need to do something like this.I have not tried to code you for you, just tried to give you an idea.I hope you can proceed.
echo '<ul>'; foreach( $fruits as $fruit){ echo '<li>' . $fruit . '</li>'; if( is_array($fruit) ){ echo '<ul>'; foreach( $fruit as $fr ){ echo '<li>' . $fr . '</li>'; } echo '</ul>'; } }echo '</ul>'; }
回答3:
<?php $fruits = array(); $fruits[] = array( 'type' => 'Banana', 'code' => 'ban00' ); $fruits[] = array( 'type' => 'Grape', 'code' => 'grp01' ); $fruits[] = array( 'type' => 'Apple', 'code' => 'apl00', array( 'subtype' => 'Green', 'code' => 'apl00gr'), array( 'subtype' => 'Red', 'code' => 'apl00r' ) ); $fruits[] = array( 'type' => 'Lemon', 'code' => 'lem00' ); iterate($fruits, 'type'); function iterate($fruits, $index) { foreach ($fruits as $fruit) { echo "<ul>"; display($fruit, $index); echo "</ul>"; } } function display($data, $index) { echo '<li><input type="checkbox" name="fruit" value="' . $data[$index] . '">' . $data[$index]; if (!empty($data[0]) && is_array($data[0])) { $newSubArray = $data; unset($newSubArray['type']); unset($newSubArray['code']); iterate($newSubArray, 'subtype'); } echo "</li>"; }