0

I've been trying to figure out a way to do this for a while now and I can't work it out at all.

product_column   product_row    product_name
__________________________________________________
1                1              product_1
1                2              product_2
1                3              product_3
2                1              product_4
2                2              product_5
2                3              product_6
3                1              product_7
3                2              product_8
3                3              product_9
4                1              product_10
4                2              product_11
4                3              product_12

That's a snippet of the table, what I'm trying to establish is a grid-like display of the products, where the product_columns are parent divs and the product_rows in these columns are child divs, like below;

<div class = "parent">
   <div class = "child">
      product_1
   </div>
   <div class = "child">
      product_2
   </div>
   <div class = "child">
      product_3
   </div>
</div>
<div class = "parent">
   <div class = "child">
      product_4
   </div>
   <div class = "child">
      product_5
   </div>
   <div class = "child">
     product_6
   </div>
</div>

Like I say I've been plugging away it for quite a while now and I've hit a stumbling block. The number of columns is not a set number either.

Thank you in advance for any help I receive.

7
  • How are you actually getting this data from your database? Commented Oct 5, 2014 at 16:53
  • I am getting the data via SQL queries Commented Oct 5, 2014 at 16:54
  • how could the number of columns in a db table not be a set ? Commented Oct 5, 2014 at 16:57
  • Not in the database table, I mean the product_column field will be updated regularly so there could be 20 or 200. Commented Oct 5, 2014 at 16:58
  • updated where ... in the database ? Commented Oct 5, 2014 at 17:08

1 Answer 1

1

You can put all the products that belongs to a column in an array with the same index, something like this:

$sql = "SELECT product_column, product_row, product_name FROM table";
$query = mysqli_query($con,$sql);
$products = array();
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){
  $products[$row['product_column']][] = $row;
}

And to iterate trough this array you can do something like this:

foreach ($products as $product_column => $list_products) {
  echo "<div class='parent'>";
    foreach($list_products as $product){
      echo "<div class='child'>".$product['product_name']."</div>";
    }  
  echo "</div>";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.