View Single Post
Old Nov 20th, 2007, 10:47 AM   #7
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
Re: Simple "foreach" problem

I'm sure you want to do more than just display the information with whatever the keys might be, and as they change from time to time, but this key-adaptive approach works for me.

Note that the tables are just 2D arrays. The foreach ($table as $row; mimics the $row = mysql_fetch_array($result);

Click "Toggle Plain Text" to see the lines unwrapped.
PHP Syntax (Toggle Plain Text)
  1. <?php
  2. $table1 = array (
  3. array ("Field1"=>"Value11", "Field2"=>"Value12", "Field3"=>"Value13"),
  4. array ("Field1"=>"Value21", "Field2"=>"Value22", "Field3"=>"Value23"),
  5. array ("Field1"=>"Value31", "Field2"=>"Value32", "Field3"=>"Value33"));
  6. $table2 = array (
  7. array ("NewName1"=>"NewValue11", "NewName2"=>"NewValue12", "NewName3"=>"NewValue13"),
  8. array ("NewName1"=>"NewValue21", "NewName2"=>"NewValue22", "NewName3"=>"NewValue23"),
  9. array ("NewName1"=>"NewValue31", "NewName2"=>"NewValue32", "NewName3"=>"NewValue33"));
  10.  
  11. function showTable ($table)
  12. {
  13. $columnHeads = array_keys ($table[0]);
  14. echo "<pre>";
  15. foreach ($columnHeads as $head)
  16. echo $head."\t\t";
  17. echo "<br>";
  18. foreach ($columnHeads as $head)
  19. {
  20. for ($i = 0; $i < strlen ($head); $i++)
  21. echo "-";
  22. echo "\t\t";
  23. }
  24. echo "<br>";
  25. foreach ($table as $row)
  26. {
  27. foreach ($columnHeads as $head) echo $row [$head]."\t\t";
  28. echo "<br>";
  29. }
  30. echo "<br>";
  31. echo "</pre>";
  32. }
  33.  
  34. showTable ($table1);
  35. showTable ($table2);
  36.  
  37. ?>
Output:
Field1		Field2		Field3		
------		------		------		
Value11		Value12		Value13		
Value21		Value22		Value23		
Value31		Value32		Value33		

NewName1		NewName2		NewName3		
--------		--------		--------		
NewValue11		NewValue12		NewValue13		
NewValue21		NewValue22		NewValue23		
NewValue31		NewValue32		NewValue33
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote