Can't figure out algorithm in php
I'm making a reservation system with one row per reservation in a mySql table. This row contains three columns: morning, afternoon and evening.
reservation_id | date | morning | afternoon | evening
int(255) | d/t | 1/0 | 1/0 | 1/0
With the use of the following GUI the user can add or subtract more or less items for the three different parts:
I'm trying to re write any possible setting (> 0) of the numbers to as less as possible rows in my reservation table. For instance:
morning | afternoon | evening
3 | 1 | 2
could be converted to (three+one+two=) 6 rows in the mysql table. But it would be nicer to transform this input to three rows:
| morning | afternoon | evening
row 1 | 1 开发者_如何学编程 | 1 | 1
row 2 | 1 | 0 | 1
row 3 | 1 | 0 | 0
Could someone help me to write this algorithm? Thank you in advance! R
//reply Every row in the table is a boat. It is strange to have in the main overview three rows for the same boat each row containing the reservation for or the morning, or the afternoon or the evening.
<?php
$data = array('morning' => 3, 'afternoon' => 2, 'evening' => 1);
for($i=0;$i<max($data);$i++) {
$m = ($data['morning']<=$i) ? 0 : 1;
$a = ($data['afternoon']<=$i) ? 0 : 1;
$e = ($data['evening']<=$i) ? 0 : 1;
mysql_query("INSERT INTO x(morning, afternoon, evening) VALUES($m, $a, $e)");
}
In pseudo-code:
while( $morning > 0 ||
$afternoon > 0 ||
$evening > 0 )
{
$thisMorning = ($morning == 0 ? 0 : 1);
$thisAfternoon = ($afternoon == 0 ? 0 : 1);
$thisEvening = ($evening == 0 ? 0 : 1);
insert_row ( $thisMorning, $thisAfternoon, $thisEvening );
if ($morning > 0) $morning--;
if ($afternoon > 0) $afternoon--;
if ($evening > 0) $evening--;
}
$morn = 3;
$aft = 2;
$eve = 1;
while($morn > 0 || $aft > 0 || $eve > 0) {
$row = array();
$row['morn'] = $morn-- > 0 ? 1 : 0;
$row['aft'] = $aft-- > 0 ? 1 : 0;
$row['eve'] = $eve-- > 0 ? 1 : 0;
$rows[] = $row;
}
Modern Computer and Modern Databases are so fast you really dont need to worry about duplication. Go with the simplest representation rather than the one with the least rows. You wont need to worry about number of rows until you hit 1,000,000 and even then its debateable.
精彩评论