Forum Moderators: coopster

Message Too Old, No Replies

Sort text file

         

smallcompany

12:22 am on Mar 1, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hi,

I have a script:
$file_name = "/file.txt";
$content = @file_get_contents ( $file_name );
$list_var = array ( );
if ( $content !== false )
{
$rows = explode ( "\n" , $content );
foreach ( $rows as $row )
{
$fields = explode ( "," , $row );
$field_name = trim ( $fields [ 0 ] );
if ( $field_name != '' )
{
$counter = trim ( isset ( $fields [ 1 ] ) ? $fields [ 1 ] : 0 );
$list_var [ $field_name ] = $counter;
}
}
}
if ( isset ( $list_var [ $urlp ] ) )
{
$list_var [ $urlp ] ++;
}
else
{
$list_var [ $urlp ] = 1;
}
$content = '';
foreach ( $list_var as $field_name => $counter )
{
$content .= $field_name . ',' . $counter . "\n";
}
file_put_contents ( $file_name , $content , LOCK_EX );


What the above does is to write the variable $urlp while counting it and writing the number as well. The outcome is this:

variable1,23
variable2,15
variable3,2327
variable4,754
...and so on...

Now I'm trying to sort those lines by the number ($counter variable), biggest to smallest. I found that sorting requires to read this flat file into an array. So far I was not able to do it, no matter how simple it sounds.

Any hint is appreciated.

Thank you

Peter_S

10:40 am on Mar 1, 2018 (gmt 0)

5+ Year Member Top Contributors Of The Month



I have a script:

Nice script! It does already what you want to! The author must be a genius!

The first part of the code already loads the file into an array:

$file_name = "/file.txt";
$content = @file_get_contents ( $file_name );
$list_var = array ( );
if ( $content !== false )
{
$rows = explode ( "\n" , $content );
foreach ( $rows as $row )
{
$fields = explode ( "," , $row );
$field_name = trim ( $fields [ 0 ] );
if ( $field_name != '' )
{
$counter = trim ( isset ( $fields [ 1 ] ) ? $fields [ 1 ] : 0 );
$list_var [ $field_name ] = $counter;
}
}
}


$list_var is your array.

To sort it:

arsort ( $list_var ) ;


Then the last part of the script browses the array, so for example if you want to render it:

foreach ( $list_var as $field_name => $counter )
{
echo $field_name . ' = ' . $counter . "<br>" ;
}

smallcompany

8:57 pm on Mar 1, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In this case, "a genius" = Peter_S :) I'll let you know how it goes.

As always, many thanks for providing the concrete code.

Cheers!

P.S.
(5 minutes later...) It works!

Peter_S

11:10 am on Mar 5, 2018 (gmt 0)

5+ Year Member Top Contributors Of The Month



In this case, "a genius" = Peter_S :)

Oh :">