Jump to content

Recommended Posts

Hello all,

 

I have a ORDER BY question. In a VARCHAR field, I have written some values like:

1

1.1

1.1.3.5

1.1.3.5.1

1.1.3.5.2

 

and so on. It is meant as a hierarchical structure.

 

Now, on ordering entries like

 

1.9

1.10

1.11

 

MySQL will order this naturally as follows:

 

1.10

1.11

1.9

 

Which is, as you will guess, not my idea. Is it somehow possible to order it in the correct way without modifying the data?

 

Link to comment
https://forums.phpfreaks.com/topic/152950-solved-order-by-issue/
Share on other sites

You can easily convert leading 0 to no leading zero by exploding the data...

 

SOURCE: 01.01.01.02.12.01

$arrElements=explode('.',$source);
$arrElements=ltrim($arrElements,'0');
$final=implode('.',$arrElements);

 

That would convert "01.01.01.02.12.01" into "1.1.1.2.12.1"

You can easily write a script to convert the existing data in your database to readable format:

$query=mysql_query("SELECT id,source FROM table");

while ($row=mysql_query($query)) {

  $arrElements=explode('.',$row['source']);

  foreach ($arrElements as $element) {

    $element=($element<9 ? '0' : '').$element;

  }

  $converted=implode('.',$arrElements);

  mysql_query("UPDATE table SET source='".$converted."' WHERE id=".$row['id'].");

}[/code]

 

Something like that.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.