Sorting, auto change value on same values

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Sorting, auto change value on same values

Post by Sindarin »

I have an 'order' column which defines the order some sql results will be ordered by. I have a form with textfields to quickly change the items' order like,

Order | Item
[ 1 ] item1
[ 2 ] item2
[ 3 ] item3
[ 4 ] item4
[ 5 ] item5
[ 6 ] item6
[ 7 ] item7
[ 8 ] item8
[ 9 ] item9

[ ReSort ]

Now the problem is that the 'order' column can have one or more equal values like,

Order | Item
[ 1 ] item1
[ 1 ] item2

[ 7 ] item3
[ 4 ] item4
[ 1 ] item5
[ 7 ] item6
[ 7 ] item7

[ 8 ] item8
[ 9 ] item9

and in that case they will be sort by order and next, for the rows that have same values, are ordered by modified date, (I think),

What I want to do is auto rearrange the values so they can never have same values,

for e.g. user changes item's 2 order value to be 1, but there is already a value 1, so when we resort the values it becomes like this,

Order | Item
[ 1 ] item2
[ 2 ] item1
[ 3 ] item3
[ 4 ] item4
[ 5 ] item5
[ 6 ] item6
[ 7 ] item7
[ 8 ] item8
[ 9 ] item9

item's 2 value changes to 1 and automatically item's 1 value (which was 1) changes to the next possible, that is 2.

Any help on this?
User avatar
andyhoneycutt
Forum Contributor
Posts: 468
Joined: Wed Aug 27, 2008 10:02 am
Location: Idaho Falls

Re: Sorting, auto change value on same values

Post by andyhoneycutt »

Code: Select all

 
// Get the key where the item we're going to re-assign resides.
$old_key = array_search($item,$order_array);
// Get the value of the item that exists where we will be moving the new item to.
$move_item = $order_array[$new_order];
// Put the value of the item at the new spot into the spot where the new item was moved from.
$order_array[$old_key] = $move_item;
// Put the value of the item we're moving into the spot we wish it to go now.
$order_array[$new_order] = $item;
Ok, not the best explanation, but I'll elaborate if you're having any trouble getting it to work.

-Andy

EDIT: Let me know if I misunderstood your post. I'm not sure that I've posted the solution you're looking for.
Post Reply