How to create a new div tag if it meets certain criteria

Hello,

This is a php issues and not a html issues.

i have a list of categories and sub categories that im trying to display like a classified ad layout but cant seem to work out the layout as to how to create a new div tag if the first div tag(column) becomes too full.

problem.
looping through a div tags(columns) and within each column i like to have 3 of the category/subCat appear. and in the event there are more then 3 sets of categories and subcategory it should create a new div tag on the right side and continue on with displaying the results . max 3 div tag(column).

how do i go about doing this…

the following code creates the categories and subcategories


foreach($dbArray1 as $value1)
	{	if(!in_array($value1['rootCategory'], $rootArr1))
		{	$rootArr1[] = $value1['rootCategory'];			
			echo '<div id="categoryBox">
				<ul id="catList1">';
					echo '<li id="catList3">' . $value1['rootCategory'] . '</li>';
						echo '<ul id="catList2">';
							foreach($dbArray1 as $value2)
							{	if($value2['rootCategory'] == $value1['rootCategory'])
								{	if(!in_array($value2['category1'], $rootArr2))
									{	$rootArr2[] = $value2['category1'];			
										if(!empty($value2['category1']))
										{	echo '<li id="catList2">' . $value2['category1'] . '</li>';
											$cat_column++;
										}					
													
									}
								}
							}
				echo '</ul>
							</ul>
			</div>';				
		} // end of if			
	}// end of foreach loop 1	



It is not easy to replicate your code without data or a screen dump of what you are trying to achieve.

When looping I introduce a counter outside the loop, within the loop test the modulus and if true then echo changes:



$counter  = 0;
foreach($dbArray1 as $value)
{
  if($counter % 3)
  {
    // $counter % 3 must be either 1 or 2 so do nothing 
  }else{
    // $counter % 3  must be ZERO so add a linefeed
    echo '<br />'; 
  }
  echo $counter % 3;
  $counter++;  

}// end of foreach loop 1 


Hi john_betong,

thanks for the reply back.

i uploaded the image. im trying to create something like kijiji layout to display the categories.
i have 10 div containers each holding a category and its respective sub categories.

  • next step is to take the 10 div tags(containing a category and subcategories) and divided it by 3 (10/3) rounded up to 4 .
  • display the first set of 4 divs tags in its own div tag. when it reaches the 4th div tag
  • display the next 4 div tags in its own div tag and again if it reaches the 4th div tag
  • display the last 2 remaining div tags within the third div tag

parent div1 parent div2 parent div3
div1 div1 div1
div2 div2 div2
div3 div3
div4 div4

Many thanks for the screen-dump, could you also supply the data:



  echo '<pre>';
    print_r( $dbArray1 ); 
  echo '</pre>';


Instead of dividing and rounding did you try using the modulus method?

hi John_Betong

i decided to simplify the example as its became harder to explain what it is that im looking for.

  • total of 22 records.
  • 22 records to be displayed within 3 div tag or columns.
  • 7 records per div tag or columns
  • each each records can be wrapped round with either a div tag or span tag.

so
create a parent div tag and display 7 records.
once it reaches the seventh record create a new div tag or column to the right of the first div tag.
again, if it reaches the seventh record, create a new div tag or column to the right of the second div tag.
posted an example image



<!DOCTYPE html>
<html>
	<head><meta charset="ISO-8859-1"><head>
	<body>
		<?php
			$animals = array( "a1"=>"dog","a2"=>"cat","a3"=>"fish", 
					   "a4"=>"bird", "a5"=>"cheetah", "a6"=>"lion", 
					   "a7"=>"greyhound", "a8"=>"tiger", "a9"=>"elephant",
					   "a10"=>"bird", "a11"=>"c12", "a13"=>"lion", 
					   "a14"=>"greyhound", "a15"=>"tiger",  "a16"=>"elephant",
					   "a17"=>"greyhound", "a18"=>"tiger",  "a19"=>"elephant",
					   "a20"=>"greyhound", "a21"=>"tiger",  "a22"=>"elephant");
					   
			$perColumn = ceil(count($animals)/3); // display number of categories per column(7)			
			$ParentColumnCount = 3; //represents the 3 outer columns
		 
			foreach($animals as $value)
			{	if( $ParentColumnCount == $perColumn)
				{	echo '<div style="border:1px solid red; float:left; width:200px; overflow:hidden;">'; }
				else
				{	echo '<span style="border:1px solid green;">'. $value . '</span><br>';
					$ParentColumnCount ++;
				}
				if($ParentColumnCount == $perColumn) 
				{	echo '</div><br><br>';  
					$perParentColumnCount = 0; 
				}		
			}
		?>	
	</body>
</html>

Try this:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.groups {float:left; width:11em; margin:0 1em 1em 0; border:1px solid red;}
</style>
<title>Title</title>
</head>
<body>
  <?php
    $animals = array
    (
    "a1"=>"dog",         "a2"=>"cat",         "a3"=>"fish", 
    "a4"=>"bird",        "a5"=>"cheetah",     "a6"=>"lion", 
    "a7"=>"greyhound",   "a8"=>"tiger",       "a9"=>"elephant",
    "a10"=>"bird",       "a11"=>"missing",    "a12"=>"spare", "a13" =>"lion", 
    "a14"=>"greyhound",  "a15"=>"big tiger",  "a16"=>"elephant",
    "a17"=>"greyhound",  "a18"=>"tiger",      "a19"=>"elephant",
    "a20"=>"greyhound",  "a21"=>"tiger",      "a22"=>"elephant",
    "a23"=>"GREYHOUND",  "a24"=>"TIGER",      "a25"=>"ELEPHANT"
    );
    // echo '<pre>'; print_r($animals); echo '</pre>';  
           
    echo '<p>Total items: ' .count($animals) .'</p>';
    $counter = 0; 
    $max     = 7; // number of items to show  in each box
    
      foreach($animals as $id => $value)
      {
        $tmp = $counter % $max; // 0..6 inclusive 

        $row = $tmp    .'&nbsp;&nbsp;' 
              . $id     .'&nbsp;&nbsp;'
              . '<b>: ' .$value . '</b><br />';

        echo $tmp ? $row : '<div class="groups">';      

        // Maybe LAST ONE?     
          echo ($tmp == $max-1) ? '</div>' : NULL;

        $counter++;   
      }
    echo '</div>';

    echo '<div style="clear:both"></div>';

    $counter =0;
    // echo '<table>';    
    if(1)
      foreach($animals as $id => $value)
      {
        $tmp = $counter % $max; // 0..6 inclusive 

        // display item
          $row =  '<tr>'
                     .'<td>'  .$tmp   .'</td>' 
                     .'<td>'   .$id    .'</td>' 
                     .'<td>'   .$value .'</td>'
                   .'</tr>';

          echo $tmp ? $row : '<table class="groups">';

        // LAST ONE?     
          echo $tmp == $max-1 ? '</table>' : NULL;

        $counter++;   
      }
      echo '</table>';    
  ?> 
</body>
</html>

hello,

not exactly what im looking for but thanks for the try… i greatly appreciate your help…

lets see what other replies we get…

If you build your array a little different, using the root as the primary key, then the category ID as the secondary key it would be somewhat easier to build display.

<?php
$dbArray1 = array();

//Built with query in while loop	
//$dbArray1[$rootCategory][$CategoryID] = $Category;

//Sample data for example
$dbArray1['For Sale'][245] = "Art, Collectibles";
$dbArray1['For Sale'][124] = "Antiques";
$dbArray1['For Sale'][247] = "Appliances";
$dbArray1['For Sale'][85] = "Baby Items"; 	
$dbArray1['For Sale'][22] = "Bicycles";
$dbArray1['For Sale'][34] = "Books";
$dbArray1['For Sale'][54] = "CDs - Records";
$dbArray1['For Sale'][25] = "Clothing";
$dbArray1['For Sale'][47] = "Computers &amp; Accessories";
$dbArray1['For Sale'][82] = "Electronics";
$dbArray1['For Sale'][65] = "Funiture";
$dbArray1['For Sale'][28] = "Home/Outdoor";
$dbArray1['For Sale'][69] = "Jewelry, watches";
$dbArray1['Pets'][2] = "Accessories";
$dbArray1['Pets'][14] = "Animal Services";
$dbArray1['Pets'][55] = "Birds for sale";
$dbArray1['Pets'][28] = "Kittens &amp; Cats";
$dbArray1['Pets'][26] = "Livestock";
$dbArray1['Pets'][37] = "Other pets and animals";
$dbArray1['Autos'][11] = "Mini Vans";
$dbArray1['Autos'][3] = "Passenger Cars";
$dbArray1['Autos'][7] = "Pickup Trucks";
$dbArray1['Autos'][83] = "Sports Cars";	
$dbArray1['Autos'][52] = "SUVs";
$dbArray1['Community'][24] = "Activities";
$dbArray1['Community'][18] = "Events";
$dbArray1['Community'][35] = "Looking for friends";
$dbArray1['Community'][84] = "Looking for long lost";
$dbArray1['Community'][69] = "Lost and Found";
$dbArray1['Community'][76] = "Musicians";
$dbArray1['Community'][62] = "Garage Sales";
$dbArray1['Community'][31] = "Ride Sharing";    							
	
										
$TotalParentCategories = count($dbArray1);
$CategoryTotals = array_map("count", $dbArray1);
$TotalCategories = array_sum($CategoryTotals);
$TotalItems = $TotalCategories + $TotalParentCategories;
$perColumn = ceil($TotalItems/3);
//Add buffer for "continued" categories
$perColumn = $perColumn+1;
////////////
?>
<html>
<head>
<style type="text/css">
.categoryBox {
float:left;
width:33%;
}

.categoryBox ul{
margin:1px auto;
}
</style>
<body>
<?php

////////////
//Start display section
$cnt=0;
$rootArr = array();	
echo '<div class="categoryBox">'."\\r";
	foreach($dbArray1 as $rootCategory => $arr1):
	
		$catcnt=0;
		foreach($dbArray1[$rootCategory] as $CategoryID => $Category):
			
			if(!in_array($rootCategory, $rootArr)):
				$rootArr[] = $rootCategory;
				//If not the first time through add </ul>	
				if($cnt>0):
					echo '</ul>'."\\r";
				endif;
								
				echo '<ul>'."\\r" .
				'<li><strong>' . $rootCategory ."</strong>\\r";
					
				echo '<ul>'."\\r";
				$cnt++;
			endif;
			
				echo '<li><a href="?id=' . $CategoryID . '">' . $Category . '</a></li>'."\\r";
							
			$catcnt++;
			//If this was the last category for this group add </ul>			
			if($catcnt == $CategoryTotals[$rootCategory]):
				echo '</ul>'."\\r";
			endif;
			
			$cnt++;
			// End div section
			if($cnt==$perColumn):
					
				echo '</ul>'."\\r";
				echo '</ul>'."\\r";
				echo '</div>
				<div class="categoryBox">'."\\r";
				//If last group has more items add Continued
				if($catcnt < $CategoryTotals[$rootCategory]){
					echo '<ul>'."\\r" .
					'<li><strong>' . $rootCategory . "</strong> continued\\r";					
					echo '<ul>'."\\r";
					$cnt=1;
				}else{  				
					echo '<ul>'."\\r";
					$cnt=0;
				}
			endif;
			
		endforeach;	
	endforeach;
	echo '</ul>'."\\r";
echo '</div>'."\\r";
?>
</body>
</html>

Hi Drummin,

Thanks for the reply back.
how do i implement your code round the database table i have. i never thought about it but i like your ideas of controlling the number of lines to ,its a better way to use up the blank space…

code used query the data


Try
{	$STM = $dbcon->prepare("SELECT cat_index, cat_parent, cat_category
		   FROM tbl_categories ");
	$STM->execute();
	$dbArray2 = $STM->fetchAll(PDO::FETCH_ASSOC);		
}   catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }



cat_index | cat_parent | cat_category
	1 	       0 		Business
 	2             0 	        Pets
	3 	       0 	        technology
 	4 	       3 	       computers
	5 	       2 	       dogs, puppies for sale
 	6 	       3 	      printer
	7 	      3 	     laptop
	8 	      2 	     cats, kittens
        9 	      3 	      tablet
 	10 	      2 	     birds, buy & sell


Hi robin01,
I believe this should do it.

$dbArray1 = array();
Try
{	$STM = $dbcon->prepare("SELECT cat_index, cat_parent, cat_category
		   FROM tbl_categories ");
	$STM->execute();
	while($row = $STM->fetch(PDO::FETCH_ASSOC)){
		//Built with query in while loop	
		$dbArray1[$row['cat_parent']][$row['cat_index']] = $row['cat_category'];	
	}		
}   catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }

EDIT: Just noticed you are using ID’s in your parent column. I’ll need to think about that and change query. You didn’t indicate this in any examples thus far.

Reference my post#4

Please supply the following raw data:



 echo '<pre>';
  print_r( $dbArray1 );    
echo '</pre>';
die;
 // please copy and paste the above data into your reply.


Here’s a corrected query to account for parent ID’s instead of Names.

$dbArray1 = array();
Try
{	$STM = $dbcon->prepare("SELECT
	q1.cat_category AS parent,
	q2.cat_index,
	q2.cat_category
	FROM tbl_categories as q1
		LEFT JOIN
		tbl_categories as q2
			ON q2.cat_parent = q1.cat_index
	WHERE q1.cat_parent = 0");
	$STM->execute();
	while($row = $STM->fetch(PDO::FETCH_ASSOC)){
		//Built with query in while loop	
		$dbArray1[$row['parent']][$row['cat_index']] = $row['cat_category'];	
	}		
}   catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }