开发者

How should I handle ordering of data while remaining flexible for future changes?

I'm working on writing a web application using php & mysql, and was wondering about the best way to approach something. The application is simple and deals with displaying boxes ("cells") which contain text. Here's the problem: I have, say, 3 cells to display: Cell A, Cell B and Cell D. In the database each has a "priority" that indicates the order in which it will be开发者_运维百科 displayed. Cell A's priority is 1, B's is 2, and D's is 3. Right now they will display in order, but when I want to add Cell C and put it between B and D, I would first need to change Cell D's priority to make room for Cell C to be in the middle.

I thought perhaps I could have the priority given at default for a new cell be a higher amount away from neighbor cells, but that would eventually fail in the same way as above.

Also, I considered using the priority field differently. Rather than using an abstract number to indicate the order, I could put the ID number of the cell that precedes it. That way, after displaying a cell, my function would do a select query to find the cell whose "priority" field is equal to the current cell's id and display it. But then the problem would be that if a cell is deleted, the next one after it (and therefore the rest in the order) would no longer show up.

What is the best way to tackle this problem?


Have a priority column that takes a decimal value, and sort by the priority. With a decimal it is very easy to fit new items in right where they belong without having to change anything else.


Rudimentary:

// $result is what our database query returned. sample data used.
$result = array(
    'name'=>'Leeroy Jenkins',
    'age'=>'28',
    'gender'=>'male',
    'note'=>'At least I\'ve got chicken.'
);

// $data contains all of the current record's information.
// the order of these is irrelevant.
$data[0] = $result['name'];
$data[1] = $result['age'];
$data[2] = $result['gender'];
$data[3] = $result['note'];

// $priority is the order what we want the information displayed in.
// change this to the preferred order using the numerical indexes from above.
// this could even be read from the database, if desired.
$priority = array(2, 1, 0, 3);

// write out our information.
foreach ($priority as $item) {
    echo '<td>' . $data[$item] . '</td>' . PHP_EOL;
}

Though duplicating the data stored in $result is probably a waste of resources.. As I stated, rudimentary.


In my forum code I simply add to the end and provide up/down buttons for each cell that simply swap the selected cell with the one above or below it which avoids the problem of inserting between.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜