Laravel 4: Generate HTML Table Like CodeIgniter - php

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

There is nothing like this in Laravel AFAIK but you may create your own, something like (an idea only) this (a php class, not only for Laravel)
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 using Laravel's rule. You may extend Html class or use as an individual class by registering it as a service. Take a look at this answer for extending a class in laravel.

Try nayjest/grids Laravel package.

You could take the script drupal uses and convert it to laravel: https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/theme_table/8
Doing a quick look at it, you would just need to replace a couple of functions:
Attributes()... I think laravel has something like this you could use. Drupal 8 is using something from symfony2 I think... laravel might be using the same thing.
_theme_table_cell(), tablesort_header(), etc... These type of functions have drupal_render() in them... you don't want to try and port that over... so you probably just delete that from the functions (untested) as it doesn't make sense in the context of laravel .
This would make for a very nice implementation of what your looking for.
EDIT: I also just ran into this: http://kohana.keyframesandcode.com/docs/modules/table/ I've not tested it but it was referenced here: http://forumsarchive.laravel.io/viewtopic.php?id=2178

Related

PHP retrieve object's getter methods only once in an array of objects

I've got an array of 20 objects that are all the same. These objects are all the same and contain a couple of properties and some getters and setters. I'm converting the property data to an HTML table like so:
public function addBody($objects) {
$ret = (string) NULL;
foreach($objects as $object) {
$ret .= '<tr>';
$methods = get_class_methods($object);
foreach($methods as $method) {
if(strpos($method, 'get') !== false) {
$ret .= '<td>' . call_user_func(array($object, $method)) . '</td>';
}
}
$ret .= '</tr>';
}
return $ret;
}
I'm iterating through my array of objects and then I get all methods of each object where I filter on only the getters (with strpos). The function works but retrieving all object methods is a waste of time. A solution I could think of is getting the first object and retrieve all its methods (getters) and use that in my addBody function.
Would this be a good solution of is there a better one?
Check this:
public function addBody($objects) {
$ret = '';
$obectMethods = get_class_methods(current($objects));
$methods = array_filter($obectMethods, function($method) {
return strpos($method, 'get') !== false;
});
foreach($objects as $object) {
$ret .= '<tr>';
foreach($methods as $method) {
$ret .= '<td>' . call_user_func(array($object, $method)) . '</td>';
}
$ret .= '</tr>';
}
return $ret;
}
First we retrieve methods from first object and use them in foreach loop.
I'm not sure about your definition of better, but sure there is another one... Less code and one getter to access any property for your specific case.
Our simple entity:
class myEntity {
private $name;
private $age;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
return null;
}
}
and then in your method:
public function addBody($entities, $properties) {
$ret = '';
foreach($entities as $entity) {
$ret .= '<tr>';
foreach($properties as $property) {
$ret .= '<td>' . $entity->__get($property) . '</td>';
}
$ret .= '</tr>';
}
return $ret;
}
where you have a list of entities:
$entities = array ( new myEntity(), new myEntity());
$properties = array ('name', 'age');
var_dump($object->addBody($entities, $properties));

yii framework. cats tree functions aren`t working in the model file

public function getCats($model){
$levels = array();
$tree = array();
$cur = array();
foreach($model as $rows){
$cur = &$levels[$rows['id']];
$cur['parent_id'] = $rows['parent_id'];
$cur['title'] = $rows['title'];
if($rows['parent_id'] == 0){
$tree[$rows['id']] = &$cur;
}
else{
$levels[$rows['parent_id']]['children'][$rows['id']] = &$cur;
}
}
return $tree;
}
public function getTree($arr){
echo '<ul>';
foreach($arr as $k=>$v){
echo '<li>';
echo ''.$v['title'].'';
if(!empty($v['children'])){
echo getTree($v['children']);
}
echo '</li>';
}
echo '</ul>';
}
public function allCats($pos) {
$model = Category::model()->findallBySql('SELECT id, parent_id, title FROM {{category}} WHERE position="'.$pos.'"');
$cats = getCats($model);
echo getTree($cats);
}
I wonder, why these functions don`t work in model file(inside class)?
If i use them inside controllers, they work fine, and if i paste them inside model(class) file, they stop working(as if they are becoming invisible). The last function causing the above two functions.
You are calling getCats($model) which would be a global function. But it's defined as a class function/method. Call it $this->getCats($model) and $this->getTree($cats) and it should work.

NotORM: How to fetch data?

I´m having trouble using selects, I tried reading the documentation but it's not too clear, and the forums that talk about it are few and inactive.
I want to do a simple select, so I tried:
$applications = $NOTORM->user_types()
->select('id, group_title')
->where('id', 1);
return $applications;
That however gives me back a NotORM object where I don't see the resulting rows that I get when I do a normal: SELECT id, group_title FROM user_types WHERE id = 1
I tried using the fetch() but not really sure how to use it. Any insights?
Actually, recommended by the author of NotORM is to use:
<?php
array_map('iterator_to_array', iterator_to_array($result));
?>
Good luck!
I had the same problem till I realized that you have to loop over result.
Try
foreach($applications as $application) {
echo $application["id"] . ": " . $application["group_title"]
}
Alternatively as you mentioned you can use fetch() which will fetch you one row at a time.
$row=$applications->fetch();
echo $row["id"];
EDIT:
To get all the row data as plain associative array instead of NotORM Object I have come across 2 techniques:
foreach($row as $key => $value) {
$data[$key]=$value;
}
$data=iterator_to_array($row); - I haven't fount a NotOrm function that does this but I found that Notorm uses this technique internally(somewhere).
To actually get only the data array of the row, you have to access NotORM_Row->row param, but it is 'protected' by default. So to use it like this:
$row = $NOTORM->user_types()
->select('id, group_title')
->where('id', 1)
->fetch()->row; //here is the magic :)
You first need to 'hack' core NotORM_Row class in 'NotORM/Row.php',
by replacing
protected $row, $result;
to
public $row, $result;
Note: You have to call fetch() on NotORM results, because it will return the NotORM_Row object where the row data is placed.
Just add this code somewhere inside the NotORM_Result class:
function result() { return (Object)$this->result_array(); }
function result_array() {
foreach($this as $row) { $ret[] = iterator_to_array($row); }
return $ret;
}
And use it like:
$applications = $NOTORM->user_types()
->select('id, group_title')
->where('id', 1);
return $applications->result(); //To return it as an Plain Object
//or
return $applications->result_array(); //To return it as a Assoc Array
Try to define this PHP function:
function getArray($obj){
$arr = array();
foreach ($obj as $objSingle) {
$arrRow = array();
foreach ($objSingle as $key => $value) {
$arrRow[$key] = $value;
}
$arr[] = $arrRow;
}
return $arr;
}
And use it by calling:
$arr = getArray($applications);
NotOrm added a function that return raw row data than names jsonSerialize. You can get row data array by this function.
Example:
$row=$db->MyTable->where('X','93054660084')->fetch();
var_dump($row->jsonSerialize());
Output:
array (size=5)
'X' => string '93054660084' (length=9)
'Idc' => string '1132' (length=4)
'IdH' => string '1' (length=1)
'Mab' => string '0' (length=1)
'Tar' => string 'xsderf' (length=10)
For multi record data you need to use foreach and apply it to all records.
It can be done like this.
function comboBuilder2($tbl, $name, $lable, $value, $value2, $value3, $selected = NULL, $cond, $sort = NULL){
global $db;
$html = '';
$sort1 = (!empty($sort)) ? "order by sort asc" : '';
$sql = "select * from " . $tbl . " " . $cond . " " . $sort1 . "";
//echo $sql;
$sth = $db->query($sql);
$rs = $sth->fetchAll();
//print_r($rs);
if ($rs[0] > 0) {
foreach ($rs as $row) {
if ($selected == $row[$value])
$sel = 'selected = "selected" ';
else
$sel = '';
echo $row[$lable];
//$html .= '<option value="' . $row[$value] . '" data-min="' . $row[$value2] . '" data-max="' . $row[$value3] . '" ' . $sel . '>' . $row[$lable] . '</option>';
}
$html .= '';
}
return $html;
}

zend form custom attribute in select option?

I want know how to add custom attribute for option in a select field of Zend form.
PHP:
$option_values = array("multiOptions" => array(
"US" => "United States",
"CA" => "Canada",
));
$type=array('big','small');
$option= new Zend_Form_Element_Select('option', $option_values);
HTML:
<select>
<option value='US' type='big'>United States</option>
<option value='CA' type='small'>Canada</option>
</select>
How to add this type attribute in the option?
It is not possible using ZF's implementation of Zend_Form_Element_Select. You need to create your own element. I have done something similar, here's the relevant code:
<?php
require_once 'Zend/Form/Element/Select.php';
/**
* Select, but with the possibility to add attributes to <option>s
* #author Dominik Marczuk
*/
class Zend_Form_Element_SelectAttribs extends Zend_Form_Element {
public $options = array();
public $helper = 'selectAttribs';
/**
* Adds a new <option>
* #param string $value value (key) used internally
* #param string $label label that is shown to the user
* #param array $attribs additional attributes
*/
public function addOption ($value,$label = '',$attribs = array()) {
$value = (string) $value;
if (!empty($label)) $label = (string) $label;
else $label = $value;
$this->options[$value] = array(
'value' => $value,
'label' => $label
) + $attribs;
return $this;
}
}
Put this into /library/Zend/Form/Element/SelectAttribs.php. You also need a helper to render the element. Put it into your view helpers directory, name it SelectAttribs.php as well. Here's the contents of my file:
<?php
require_once 'Zend/View/Helper/FormElement.php';
class Zend_View_Helper_SelectAttribs extends Zend_View_Helper_FormElement {
public function selectAttribs($name, $value = null, $attribs = null, $options = null, $listsep = "<br />\n") {
$info = $this->_getInfo($name, $value, $attribs, $options, $listsep);
extract($info); // name, id, value, attribs, options, listsep, disable
// force $value to array so we can compare multiple values to multiple
// options; also ensure it's a string for comparison purposes.
$value = array_map('strval', (array) $value);
// now start building the XHTML.
$disabled = '';
if (true === $disable) {
$disabled = ' disabled="disabled"';
}
// Build the surrounding select element first.
$xhtml = '<select'
. ' name="' . $this->view->escape($name) . '"'
. ' id="' . $this->view->escape($id) . '"'
. $disabled
. $this->_htmlAttribs($attribs)
. ">\n ";
// build the list of options
$list = array();
$translator = $this->getTranslator();
foreach ($options as $opt_value => $option) {
$opt_disable = '';
if (is_array($disable) && in_array($opt_value, $disable)) {
$opt_disable = ' disabled="disabled"';
}
$list[] = $this->_build($option, $disabled);
}
// add the options to the xhtml and close the select
$xhtml .= implode("\n ", $list) . "\n</select>";
return $xhtml;
}
protected function _build($option, $disabled) {
$html = '<option';
foreach ($option as $attrib => $value) {
$html .= " $attrib=\"$value\"";
}
return $html.$disabled.">".$option['label']."</option>";
}
}
With this, you should be ready to go:
$elt = new Zend_Form_Element_SelectAttribs('whatever');
$elt->addOption($value,$label,array('attribname' => 'attribvalue'));
Using addMultiOption($value,$label) I just set the value parameter to something like:
$value = $id . '" ref="' . $ref;
and when it renders you get:
<option value="<idValue>" ref="<refValue"><labelValue></option>
Hope this helps....
Okay, value gets escaped but optionClasses does not so inside the loop that adds the addMultiOptions(val,lable) I do something like this:
$optionClasses[<val>] = 'ref_' . <val> . '" ref="' . <ref>;
and then after the loop just do a setAttrib('optionClasses',$optionClasses)
And that actually works...
I answered this for another question but could not find a way to add a comment here to reference it; It was Zend Framework addMultiOption adding custom parameters like "rel" for options
I didn't find #mingos's answer complete and had some issues with implementing setting the value. His answer helped a lot with what needed to be extended and changed however. Once I had that start the rest was pretty easy. I just extended ZF1's Select and overrode where I needed:
/**
* Select, now with abbility to specify attributes on <Option>, addMultiOption has new syntax
* #author Seth Miller
*/
class MyNamespace_Form_Element_SelectAttribs extends Zend_Form_Element_Select {
public $options = array();
public $helper = 'selectAttribs';
/**
* Add an option
*
* #param string $option
* #param string $value
* #return Zend_Form_Element_Multi
*/
public function addMultiOption($value, $label = '', $attribs = array()) {
$value = (string) $value;
if (!empty($label)) {
$label = (string) $label;
}
else {
$label = $value;
}
$this->_getMultiOptions();
if (!$this->_translateOption($value, $label)) {
$this->options[$value] = array(
'value' => $value,
'label' => $label
) + $attribs;
}
return $this;
}
/**
* Add many options at once
*
* #param array $options
* #return Zend_Form_Element_Multi
*/
public function addMultiOptions(array $options) {
foreach ($options as $optionKey => $optionProperties) {
if (is_array($optionProperties)
&& array_key_exists('key', $optionProperties)
&& array_key_exists('value', $optionProperties)
) {
if(array_key_exists('key', $optionProperties)) $optionKey = $optionProperties['key'];
$this->addMultiOption($optionKey, $optionProperties['value'], $optionProperties['attribs']);
}
else {
$this->addMultiOption($optionKey, $optionProperties);
}
}
return $this;
}
public function isValid($value, $context = null)
{
if ($this->registerInArrayValidator()) {
if (!$this->getValidator('InArray')) {
$multiOptions = $this->getMultiOptions();
$options = array();
foreach ($multiOptions as $optionKey => $optionData) {
// optgroup instead of option label
if (is_array($optionData['options'])) {
$options = array_merge($options, array_keys($optionData['options']));
}
else {
$options[] = $optionKey;
}
}
$this->addValidator(
'InArray',
true,
array($options)
);
}
}
return parent::isValid($value, $context);
}
}
And the view helper:
class MyNamespace_View_Helper_SelectAttribs extends Zend_View_Helper_FormElement {
public function selectAttribs($name, $value = null, $attribs = null, $options = null, $listsep = "<br />\n") {
$info = $this->_getInfo($name, $value, $attribs, $options, $listsep);
extract($info); // name, id, value, attribs, options, listsep, disable
// force $value to array so we can compare multiple values to multiple
// options; also ensure it's a string for comparison purposes.
$value = array_map('strval', (array) $value);
// check if element may have multiple values
$multiple = '';
if (substr($name, -2) == '[]') {
// multiple implied by the name
$multiple = ' multiple="multiple"';
}
if (isset($attribs['multiple'])) {
// Attribute set
if ($attribs['multiple']) {
// True attribute; set multiple attribute
$multiple = ' multiple="multiple"';
// Make sure name indicates multiple values are allowed
if (!empty($multiple) && (substr($name, -2) != '[]')) {
$name .= '[]';
}
}
else {
// False attribute; ensure attribute not set
$multiple = '';
}
unset($attribs['multiple']);
}
// now start building the XHTML.
$disabled = '';
if (true === $disable) {
$disabled = ' disabled="disabled"';
}
// Build the surrounding select element first.
$xhtml = '<select'
.' name="'.$this->view->escape($name).'"'
.' id="'.$this->view->escape($id).'"'
.$multiple
.$disabled
.$this->_htmlAttribs($attribs)
.">\n ";
// build the list of options
$list = array();
$translator = $this->getTranslator();
foreach ((array) $options as $optionKey => $optionData) {
if (isset($optionData['options'])) {
$optDisable = '';
if (is_array($disable) && in_array($optionData['value'], $disable)) {
$optDisable = ' disabled="disabled"';
}
if (null !== $translator) {
$optValue = $translator->translate($optionData['value']);
}
$optId = ' id="'.$this->view->escape($id).'-optgroup-'
.$this->view->escape($optionData['value']).'"';
$list[] = '<optgroup'
.$optDisable
.$optId
.' label="'.$this->view->escape($optionData['value']).'">';
foreach ($optionData['options'] as $optionKey2 => $optionData2) {
$list[] = $this->_build($optionKey2, $optionData2, $value, $disable);
}
$list[] = '</optgroup>';
}
else {
$list[] = $this->_build($optionKey, $optionData, $value, $disable);
}
}
// add the options to the xhtml and close the select
$xhtml .= implode("\n ", $list)."\n</select>";
return $xhtml;
}
/**
* Builds the actual <option> tag
*
* #param string $value Options Value
* #param string $label Options Label
* #param array $selected The option value(s) to mark as 'selected'
* #param array|bool $disable Whether the select is disabled, or individual options are
* #return string Option Tag XHTML
*/
protected function _build($optionKey, $optionData, $selected, $disable)
{
if (is_bool($disable)) {
$disable = array();
}
$opt = '<option';
foreach ($optionData as $attrib => $attribValue) {
$opt .= ' '.$this->view->escape($attrib).'="'.$this->view->escape($attribValue).'"';
}
// selected?
if (in_array((string) $optionData['value'], $selected)) {
$opt .= ' selected="selected"';
}
// disabled?
if (in_array($optionData['value'], $disable)) {
$opt .= ' disabled="disabled"';
}
$opt .= '>' . $this->view->escape($optionData['label']) . "</option>";
return $opt;
}
}
And implementation in a form would be something like:
$selectElement = new MyNamespace_Form_Element_SelectAttribs('selectElementName');
$selectElement->addMultiOption($value, $label, array('data-custom' => 'custom data embedded in option tag.');
I hope that helps someone. Thanks.
mingos,
you forgot about setvalue method of multiselect.
you shoul add something like:
...
foreach ($options as $opt_value => $option) {
$opt_disable = '';
$opt_selected = '';
if (is_array($disable) && in_array($opt_value, $disable)) {
$opt_disable = ' disabled="disabled"';
}
if (in_array($opt_value,$value)) {
$opt_selected = ' selected="selected"';
}
$list[] = $this->_build($option, $disabled, $opt_selected);
}
...
and
protected function _build($option, $disabled, $opt_selected) {
$html = '<option';
foreach ($option as $attrib => $value) {
$html .= " $attrib=\"$value\"";
}
return $html . $disabled . $opt_selected . " foo>" . $option['label'] . "</option>";
}
You could extend / overwrite the Zend_View_Helper_FormSelect helper but the real problem is going to be getting the extra data into each option.
By default, Zend_Form_Element_Select (via Zend_Form_Element_Multi) expects two strings for each option, one for the value attribute and an optional one for the text content. You may need to create your own element to handle the extra data.
No need for custom form element at all, what u can do is:
$element->setAttrib('disable', array(1, 2, 5));
As explained at http://pietervogelaar.nl/set-attribute-on-select-option-with-zend_form/
use Zend\Form\Element;
use Zend\Form\Form;
$select = new Element\Select('language');
$select->setLabel('Which is your mother tongue?');
$select->setValueOptions([
[
'value' => '0',
'label' => 'French',
'attributes' => [
'data-locale' => 'fr'
],
],
[
'value' => '1',
'label' => 'Italian',
'disabled' => true,
],
]);
$form = new Form('language');
$form->add($select);
I found this way much easier than any of the above suggestions

PHP loop optimization

I have a php method that creates an HTML table with data it retrieves from a property.
My biggest concern is the performance of my application because I deal with a large amount of data.
public function getHTML() {
$phpObj = json_decode($this->data); // array(object, object, object, ....);
$table = "<table><tbody>\n";
if (count($phpObj->query->results->row) > 0) {
$row = $phpObj->query->results->row;
foreach ($row as $value) {
$table .= "<tr>\n";
foreach ($value as $key => $val) { // concerned about loop inside loop
$table .= "<td>" . $value->$key . "</td>";
}
$table .= "\n</tr>\n";
}
$table .= "</tbody></table>";
return $table;
}
else {
return 'HTML table not created.';
}
}
Is there a more efficient way of traversing through the array and objects without creating a loop inside a loop?
Don't concatenate and return the value, echo it immediately instead. Less clean but the performance will be much more interesting since the strings are immediately outputed to the output buffer which is managed more efficiently.
A loop inside a loop is often the best way to traverse a two-dimensional array.
String concatenation is cost-intensive. You could reduce the number of repetitive string concatenations by using arrays:
public function getHTML() {
$phpObj = json_decode($this->data);
if (count($phpObj->query->results->row) > 0) {
$rows = array();
foreach ($phpObj->query->results->row as $row) {
$cells = array();
$rows[] = "<td>" . implode("</td><td>", $row) . "</td>";
}
return "<table><tbody>\n<tr>\n" .
implode("\n<tr>\n<tr>\n", $rows) .
"\n</tr>\n</tbody></table>";
} else {
return 'HTML table not created.';
}
}
You could also use anonymous functions (available since PHP 5.3):
public function getHTML() {
$phpObj = json_decode($this->data);
if (count($phpObj->query->results->row) > 0) {
return "<table><tbody>\n<tr>\n" .
implode("\n<tr>\n<tr>\n", array_map(function($cells) { return "<td>".implode("</td><td>", $cells)."</td>"; }, $phpObj->query->results->row)) .
"\n</tr>\n</tbody></table>";
} else {
return 'HTML table not created.';
}
}
UPDATE
Col. Shrapnel correctly stated that, oddly, string concatenation is actually relatively fast in php.
As Vincent said, don't run a bunch of concatenations, that's killing you. You have two options to speed up your script:
Echo immediately.
Store your lines in a an array, and join the array at the end.
Example of two:
<?php
$mylines = array();
foreach ($row as $value) {
$mylines[] = "<tr>\n";
foreach ($value as $key => $val) { // concerned about loop inside loop
$mylines[] = "<td>" . $value->$key . "</td>";
}
$mylines[] = "\n</tr>\n";
}
return implode('', $mylines);
You could move the HTML building into the frontend and ship the JSON data to the user via AJAX and javascript.
This could also allow your to only ship pieces of the data at a time (depending on your html layout), so they could be dynamically polled when needed (like google/bing image search).
I know I didn't answer the question directly. That is because the code you have is probably the fastest it can be done (in PHP) w/o doing silly little optimizations that would only make the code harder to read/maintain (probably only save a few % anyway).
EDIT: after looking at it again, I bet your code is actually just polling the data from an external source in JSON. You could probably remove this code completely by having the frontend javascript do the HTTP hit and deal with the data there. This removes the need for this PHP code to run at all.
EDIT 2: after reading your comment about this being a fall back for javascript being disabled, I looked at the code your currently doing. It appears to be translatable into implode.
//declared this functions somewhere
function tr_build( $row_value )
{
$tablerow .= "<tr>\n";
if( $row_value ) {
$tablerow .= "<td>".implode( "</td><td>", $row_value )."</td>";
}
$tablerow .= "\n</tr>\n";
return $tablerow;
}
//this replaces the double loop
if( $row ) {
$tablerows = "<tr>\n".implode( "\n</tr>\n<tr>\n", array_map( "tr_build", $row ) )."\n</tr>\n"
} else {
$tablerows = "";
}
Why are you bothering with this?
$table .= "<tr>\n";
foreach ($value as $key => $val) { // concerned about loop inside loop
$table .= "<td>" . $value->$key . "</td>";
}
$table .= "\n</tr>\n";
You never actually use $val so why have this loop at all?
$table .= "<table><td>";
$table .= implode("</td><td>", array_keys($value));
$table .= "</td></table>";

Categories