Skip to content
cadorn edited this page Feb 10, 2011 · 1 revision

cFreed: 2009-05-30: extended table() method proposal

1. Purpose

Till 0.2.3, table() method expected $table argument to be a simple array (i.e. with numeric indices only. With 0.3, it has been extended so $table may be either a simple or associative array. But keys are simply ignored. In my own work I frequently need to look at the contents of a SQL query, obtained through a PHP mysql_fetch_assoc(), so the result is an associative array where keys are field names.

My extended table() method proposal uses heuristics to detect such an array and use keys to build a header with field names, and insert it as the very first row of the actually displayed table.

The heuristic strategy is:

  • header is built if first row contains only string keys
  • it is finally inserted if each row contained the same keys set

2. How to test

Comment whole protected function encodeTable() (FirePHP.class.php, lines 981-1000). Under this commented bloc, insert code below.

Then use FirePHP::table() to log either simple, associative or "SQL" arrays... Hope it helps, and hope it works :-)

3. Code

    protected function encodeTable($Table) {
      #function _encodeTable($Table) {
      if(!$Table) return $Table;
      # initialize a new table, reserving a place for header:
      $newTable[]=array();
      foreach($Table as $num=>$row) {
        if(is_array($row)) {
          $header=array();
          foreach($row as $key=>$item) {
            # try to build header from keys:
            if(!@$remove_header) {
              # (or already cancelled)
              if(is_int($key)) {
                # numeric key found, must cancel:
                $remove_header=true;
              }
              else {
                $header[]=$key; # populate header
              }
            }
            # in any case, ensure to remove string keys:
            $newTable[$num+1][]=$this->encodeObject($item);
          }
          # then, for the entire row:
          if(!$newTable[0]) {
            # first row, register header:
            $newTable[0]=@$header;
          }
          else {
            if(array_intersect($header,$newTable[0])<>$header) {
              # header not constant through rows, must cancel:
              $remove_header=true;
            }
          }
        }
        else {
          # row exist which are not arrays, table cannot be viewed as DB one:
          $remove_header=true;
        }
      }
      if(@$remove_header) unset($newTable[0]);
      return $newTable;
    }