SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Non-Member
    Join Date
    Sep 2013
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How can I display a 2 dimensonal array?

    How can I display a 2 dimensonal array?

  2. #2
    Community Advisor silver trophybronze trophy
    dresden_phoenix's Avatar
    Join Date
    Jun 2008
    Location
    Madison, WI
    Posts
    2,791
    Mentioned
    34 Post(s)
    Tagged
    2 Thread(s)
    The question is kind of vague. It really depends on your data, what it represents.

    Most likely you WANT to display it as a TABLE . with one key being column head the other rows.

    For example, if you are using PHP:

    Code:
    <table ><?
    // $twoDarray is your array
    function renderTDs( $cells, $tag='td',$rhead=true,$row=false)  {
    	$firstTD=true;
     	foreach ( $cells as  $cont){
     		if ($rhead && $firstTD){echo '<th>',$row,"</th>\n";}
    		echo  "<$tag>",$cont,"</$tag>\n";
    		$firstTD=false;
     	}
    }
    
    function renderTable( $twoDarray, $rhead=true,$chead=true)  {
     	if ($chead){
     	    echo '<thead>';
     	    if ($rhead){echo '<th></th>';}
     		$ths=array_keys($twoDarray);
     		$ths=array_keys($twoDarray[$ths[0]]);
    		renderTDs($ths, $tag='th',false);
    		echo "</thead>\n";
    
    	}
    	foreach ( $twoDarray as $row=>$cells){
    		echo '<tr>';
    		renderTDs($cells,'td',$rhead,$row);
     		echo "<tr>\n";
    	
    	 }
    }
    $twoDarray['row1']['col1']=1;
    $twoDarray['row1']['col2']=1;
    $twoDarray['row1']['col3']=1;
    $twoDarray['row1']['col4']=1;
    $twoDarray['row2']['col1']=1;
    $twoDarray['row2']['col2']=1;
    $twoDarray['row2']['col3']=1;
    $twoDarray['row2']['col4']=1;
    renderTable($twoDarray);
    ?>
    </table>
    (hastily put together as am on the phone with a client)
    $twoDarray is YOUR array.
    if you want a table with column and row heads : renderTable($twoDarray);
    if you want a table with column heads : renderTable($twoDarray,false);
    if you want a table with row heads, but no col head : renderTable($twoDarray,true,false);
    if you want a table with no heads : renderTable($twoDarray,false,false);

    hope that helps

  3. #3
    #titanic {float:none} silver trophy
    molona's Avatar
    Join Date
    Feb 2005
    Location
    from Madrid to Heaven
    Posts
    8,179
    Mentioned
    234 Post(s)
    Tagged
    1 Thread(s)
    As @dresden_phoenix ; said, the question is vague and hard to answer precisely for that very reason. Being specific pays off, I can assure you.

    Dresden has given you an example in PHP but... is this the language you need?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •