Jump to content

[SOLVED] order by issue


friedemann_bach

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.