Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中根据每个txt文件的第二行对txt文件进行排序_Php_Arrays_Sorting_Foreach - Fatal编程技术网

如何在php中根据每个txt文件的第二行对txt文件进行排序

如何在php中根据每个txt文件的第二行对txt文件进行排序,php,arrays,sorting,foreach,Php,Arrays,Sorting,Foreach,我有几个.txt文件,其中包含几行代码。每个txt文件的名称都有一个唯一的id: 20191205140624.txt 20191206140309.txt and so on... 所有的txt文件都在messages文件夹中,我通过以下代码读取它们: // read all files in messages folder $dir = 'messages/'; if ($dh = opendir($dir)) { while(($file = readdir($dh))!== f

我有几个
.txt
文件,其中包含几行代码。每个txt文件的名称都有一个唯一的id:

20191205140624.txt
20191206140309.txt
and so on...
所有的txt文件都在messages文件夹中,我通过以下代码读取它们:

// read all files in messages folder
$dir = 'messages/';
if ($dh = opendir($dir)) {
    while(($file = readdir($dh))!== false){
        if ($file != "." && $file != "..") { // This line strips out . & ..         
            $entrylist[] = $file;   

            $lines = file($dir.$file);
            $secondline = $lines[1]; // grab the second line   
            $globalArray[] = $secondline;   // put all second lines in an array         
        }

    }   
    sort($globalArray); // sort array
    print_r($globalArray); // show me the array
}
因此var
$entrylist
是所有txt文件的数组。 和
print\r($globalArray)
显示基于姓氏的排序数组

要输出txt文件,我使用foreach:

// sort array
sort($entrylist);

foreach($entrylist as $file){
    $entryfiles = 'messages/'.$file;
    $lines = file($entryfiles, FILE_IGNORE_NEW_LINES);// filedata into an array
    $file_id = $lines[0]; // file id
    $surname= $lines[1]; //  surname
    $address= $lines[3];
    and so on...

我的问题:

如何根据每个文件的第二行(姓氏)对foreach中的所有txt文件进行排序


因此,我想要实现的是:
sort($entrylist)基于每个txt文件的第二行

存储文件名时,最好使用名称作为姓氏数组中的键。然后,您可以对数据进行排序,使键与数据保持一致,以便文件名保留在排序后的输出中(使用
asort()
而不是
sort()
)。然后可以对结果执行
foreach()
,索引是您的文件名

if ($dh = opendir($dir)) {
    while(($file = readdir($dh))!== false){
        if ($file != "." && $file != "..") { // This line strips out . & ..
            $lines = file($dir.$file);
            $secondline = $lines[1]; // grab the second line
            $globalArray[$file] = $secondline;   // put all lines in array indexed by file name
        }

    }
    asort($globalArray); // sort array preserving keys
    print_r($globalArray); // show me the array

    foreach($globalArray as $file => $surname){

        echo $file.PHP_EOL;
    }
}
我糟糕的测试数据显示

Array
(
    [10.csv] => jones

    [1.csv] => blogs

)
1.csv
10.csv