将php多维数组输出到html列表(Output php multidimensional array to html list)
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
- Banana
- Grape
Apple
- Green
- Red
- Lemon
盾畳圭宛
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=’
‘;
foreach ($data as $item) {
$html .=’
‘;
foreach ($item as $key=> $value) {
if (is_array($value)) {
$html .=renderList($value);
} else {
$html .=$value;
}
}
$html .=’
‘;
}
$html .=’
‘;
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: ABCD
Or in html form:
- A
B
- C
- D
还没有评论,来说两句吧...