Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array from file (PHP)?

Tags:

php

I have a file here which contains list of database names and its corresponding size. Now I want to sort the size from the largest to the lowest, and the database name should go along it upon display.Am using PHP here.. Can anyone help me out?

Here's a simple code for that:

$file_name = test.txt
$handle = @fopen($file_name, "r");

if ($handle) {
    while (!feof($handle)) {

    $buffer = fgets($handle, 4096);
        $data = explode(" ",$buffer);
       echo $data[1]."\n";
    }
    fclose($handle);
}

File looks like this:

DatabaseName 300 KB 

Note: $data[1] contains the sizes. Should i place it on an array? how about the db name?

Answers are very much appreciated. =)

like image 569
Suezy Avatar asked Feb 01 '26 13:02

Suezy


2 Answers

First you need to build an array with an element you can actually sort on, then use usort or similar to perform the sort based on your custom criteria.

//first build up an array of databases with a unified size in bytes, ensuring
//we account for those postfixes like KB,MB,and GB
$databases=array();
while (!feof($handle)) {

    $buffer = fgets($handle, 4096);
    $data = explode(" ",$buffer);
    if (count($data)==3)
    {
        $size=$data[1];
        switch ($data[2])
        {
            case 'KB': $size*=1024; break;
            case 'MB': $size*=1024*1024; break;
            case 'GB': $size*=1024*1024*1024; break;
        }

        $data[3]=$size;
        $databases[]=$data; 
    }
    else
    {
        die("Bad line in file: $buffer");
    }
}

Now sort with a custom comparison function to sort from high to low based on that calculated size:

function cmp($a, $b)
{
    if ($a[3] == $b[3]) {
        return 0;
    }
    return ($a[3] < $b[3]) ? 1 : -1;
}

usort($databases, "cmp");
like image 60
Paul Dixon Avatar answered Feb 04 '26 03:02

Paul Dixon


You can use the file() PHP function here.

Your text file is like :

DatabaseName 300 KB
DatabaseName 300 KB
DatabaseName 300 KB
DatabaseName 300 KB

I think you can use the PHP native function on arrays.

$data = file('myfile.txt');

foreach($data as $one_line)
{
    $db[] = explode(" ",$one_line)
    //will have $db[0][0] = 'dbname';
    //will have $db[0][2] = '30';
    //will have $db[0][2] = 'KB';   
    //will have $db[1][0] = 'dbname';
    //will have $db[1][3] = '30';
    //will have $db[1][2] = 'KB';
}
array_multisort($db[1], SORT_NUMERIC, SORT_DESC);

See this comment in documentation, the same structure : https://www.php.net/manual/en/function.array-multisort.php#79491

Or maybe you have to flip the array, so you can have size in index and name in value.

like image 20
mere-teresa Avatar answered Feb 04 '26 01:02

mere-teresa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!