开发者

PHP add paired values to array, then sort and print

开发者 https://www.devze.com 2023-02-02 09:00 出处:网络
Say I开发者_Python百科 have the name of a file and it\'s full path in two variables, how can I add them to an array, sort the array by the filename (keeping the two values paired, then loop through th

Say I开发者_Python百科 have the name of a file and it's full path in two variables, how can I add them to an array, sort the array by the filename (keeping the two values paired, then loop through the array and print it? This is using a directory iterator. I won't list the whole code as it's quite convuluted, so heres a simplified version of what I'm trying to do:

<?php

$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($pathToIterate));

foreach($files as $file){

$path=str_replace($_SERVER["DOCUMENT_ROOT"],'',$file->getPathname());
$file_name = basename($path,'.'.$info['extension']);

  // Need code to add $file_name and $path to array //

    };
} 


// Need code to sort array by $file_name //

// Need code to loop through array and print <a href="$path">$file_name</a> //


}
?>


$output = array();

foreach ($files as $file) {
   $path = ... ;
   $file_name = ... ;
   $output[$file_name][] = $path;
}

ksort($output);

foreach ($output as $file_name => $path_names) {
   sort($path_names);  // if necessary
   foreach ($path_names as $path) {
// print stuff
   }
}

EDIT: Updated thanks to elusive's suggestion


I would maintain each pair in a simple class. Then I would use usort(), which allows you to sort an array using a user-defined comparison function.

It's been a while since I've written any PHP, so I might be embarrassing myself with the following (untested) example code, but you should get the idea:

class Pair
{
    public $path;
    public $name;
}

function myComparator($p1, $p2)
{
    return strcmp($p1->name, $p2->name);
}

...

foreach ($files as $file)
{
    ...
    $p = new Pair();
    $p->path = $path;
    $p->name = $name;
    $pairs[] = $p;
}


usort($pairs, myComparator);
0

精彩评论

暂无评论...
验证码 换一张
取 消