So in CodeIgniter, there was a cool feature of creating an HTML table just by passing it an array and it handles the header, etc. Is there ANYTHING out there for Laravel, has anybody been able to use the CI version in Laravel? just asking around
3条回答 默认 最新
- dscs63759 2013-10-29 22:44关注
There is nothing like this in
Laravel
AFAIK but you may create your own, something like (an idea only) this (aphp
class, not only forLaravel
)class Table { protected $table = null; protected $header = null; protected $attr = null; protected $data = null; public function __construct($data = null, $attr = null, $header = null) { if(is_null($data)) return; $this->data = $data; $this->attr = $attr; if(is_array($header)) { $this->header = $header; } else { if(count($this->data) && $this->is_assoc($this->data[0]) || is_object($this->data[0])) { $headerKeys = is_object($this->data[0]) ? array_keys((array)$this->data[0]) : array_keys($this->data[0]); $this->header = array(); foreach ($headerKeys as $value) { $this->header[] = $value; } } } return $this; } public function build() { $atts = ''; if(!is_null($this->attr)) { foreach ($this->attr as $key => $value) { $atts .= $key . ' = "' . $value . '" '; } } $table = '<table ' . $atts . ' >'; if(!is_null($this->header)) { $table .= '<thead><tr>'; foreach ($this->header as $value) { $table .= '<th>' . ucfirst($value) . '</th>'; } $table .= '</thead></tr>'; } $table .= '<tbody>'; foreach ($this->data as $value) { $table .= $this->createRow($value); } $table .= '</tbody>'; $table .= '</table>'; return $this->table = $table; } protected function createRow($array = null) { if(is_null($array)) return false; $row = '<tr>'; foreach ($array as $value) { $row .= '<td>' . $value . '</td>'; } $row .= '</tr>'; return $row; } protected function is_assoc($array){ return is_array($array) && array_diff_key($array, array_keys(array_keys($array))); } }
Now, you can use it as given below (An Example Here.)
$data = array( array('name' => 'Heera', 'age'=>'35', 'address' =>'Masimpur', 'phone'=>'123456'), array('name' => 'Usman', 'age'=>'28', 'address' =>'Kamal Gor', 'phone'=>'654321') ); $attr = array('class'=>'tbl someClass', 'id'=>'myTbl', 'style'=>'width:400px;color:red', 'border'=>'1'); $t = new Table($data, $attr); echo $t->build();
Or, set an header using third argument, like
$t = new Table($data, $attr, array('Known As', 'Years', 'Location', 'Contact'));
This is just an idea and could be better. Now just integrate this class with
Laravel
usingLaravel
's rule. You may extendHtml
class or use as an individual class by registering it as a service. Take a look at this answer for extending a class inlaravel
.本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报