如何从PHP数组创建HTML表?

如何从PHP数组创建HTML表?标题为'title','price'和'number'的表。


$shop = array(

    array("rose",   1.25, 15),

    array("daisy",  0.75, 25),

    array("orchid", 1.15, 7 ),

); 


撒科打诨
浏览 499回答 3
3回答

Cats萌萌

这是我的:<?php&nbsp; &nbsp; function build_table($array){&nbsp; &nbsp; // start table&nbsp; &nbsp; $html = '<table>';&nbsp; &nbsp; // header row&nbsp; &nbsp; $html .= '<tr>';&nbsp; &nbsp; foreach($array[0] as $key=>$value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $html .= '<th>' . htmlspecialchars($key) . '</th>';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; $html .= '</tr>';&nbsp; &nbsp; // data rows&nbsp; &nbsp; foreach( $array as $key=>$value){&nbsp; &nbsp; &nbsp; &nbsp; $html .= '<tr>';&nbsp; &nbsp; &nbsp; &nbsp; foreach($value as $key2=>$value2){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $html .= '<td>' . htmlspecialchars($value2) . '</td>';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $html .= '</tr>';&nbsp; &nbsp; }&nbsp; &nbsp; // finish table and return it&nbsp; &nbsp; $html .= '</table>';&nbsp; &nbsp; return $html;}$array = array(&nbsp; &nbsp; array('first'=>'tom', 'last'=>'smith', 'email'=>'tom@example.org', 'company'=>'example ltd'),&nbsp; &nbsp; array('first'=>'hugh', 'last'=>'blogs', 'email'=>'hugh@example.org', 'company'=>'example ltd'),&nbsp; &nbsp; array('first'=>'steph', 'last'=>'brown', 'email'=>'steph@example.org', 'company'=>'example ltd'));echo build_table($array);?>

qq_遁去的一_1

<table>&nbsp; &nbsp; &nbsp;<tr>&nbsp; &nbsp; &nbsp; &nbsp;<td>title</td>&nbsp; &nbsp; &nbsp; &nbsp;<td>price</td>&nbsp; &nbsp; &nbsp; &nbsp;<td>number</td>&nbsp; &nbsp; &nbsp;</tr>&nbsp; &nbsp; &nbsp;<? foreach ($shop as $row) : ?>&nbsp; &nbsp; &nbsp;<tr>&nbsp; &nbsp; &nbsp; &nbsp;<td><? echo $row[0]; ?></td>&nbsp; &nbsp; &nbsp; &nbsp;<td><? echo $row[1]; ?></td>&nbsp; &nbsp; &nbsp; &nbsp;<td><? echo $row[2]; ?></td>&nbsp; &nbsp; &nbsp;</tr>&nbsp; &nbsp; &nbsp;<? endforeach; ?>&nbsp; &nbsp;</table>
打开App,查看更多内容
随时随地看视频慕课网APP