【问题标题】:Array isn't sorting when writing to file写入文件时数组未排序
【发布时间】:2015-04-25 21:46:10
【问题描述】:

我写了这个脚本:

<?PHP
$file_handle = fopen("info.txt", "rb");
while (!feof($file_handle) ) {
    $line_of_text = fgets($file_handle);
    $parts[] = explode('|', $line_of_text);
}

fclose($file_handle);
$a = $parts;

function cmp($a,$b){
    return strtotime($a[8])<strtotime($b[8])?1:-1;
};

uasort($a, 'cmp');
$failas = "dinfo.txt";
$fh = fopen($failas, 'w');

for($i=0; $i<count($a); $i++){
    $txt=implode('|', $a[$i]);
    fwrite($fh, $txt);
}
fclose($fh);
?>

当我使用时:

print_r($a);

之后

uasort($a, 'cmp');

然后我可以看到排序的数组。但是当我使用这些命令写入文件时:

$fh=fopen($failas, 'w');
for($i=0; $i<count($a); $i++){
    $txt=implode('|', $a[$i]);
    fwrite($fh, $txt);
}
fclose($fh);

它显示未排序的信息,我做错了什么?

【问题讨论】:

    标签: php file sorting text implode


    【解决方案1】:

    这应该适合你:

    在这里,我首先将您的文件放入带有file() 的数组中,其中每一行都是一个数组元素。在那里我忽略了每行末尾的空行和换行符。

    在此之后,我使用usort() 对数组进行排序。我首先通过explode()'ing 从每一行获取所有日期和时间。在此之后,我只需使用strtotime() 获取每个日期的时间戳并将其相互比较。

    最后我只是用file_put_contents()保存文件,我还在每行末尾添加一个换行符array_map()

    <?php
    
        $lines = file("test.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
    
        usort($lines, function($a, $b){
            list($aDate, $aTime) = explode(" ", explode("|", $a)[substr_count($a, "|")]);
            list($bDate, $bTime) = explode(" ", explode("|", $b)[substr_count($b, "|")]);
    
            if(strtotime("$aDate $aTime") == strtotime("$bDate $bTime"))
                return 0;
            return strtotime("$aDate $aTime") < strtotime("$bDate $bTime") ? 1 : -1;
        });
    
        file_put_contents("test.txt", array_map(function($v){return $v . PHP_EOL;}, $lines));
    
    ?>
    

    旁注:

    我建议您将这些数据保存在数据库中,这样可以灵活地对数据进行排序和获取!

    编辑:

    对于 echo phpversion();) 的人,只需将匿名函数更改为普通函数并将函数名称作为字符串传递,如下所示:

    <?php
    
        $lines = file("test.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
    
        function timestampCmp($a, $b) {
            $aExploded = explode("|", $a);
            $bExploded = explode("|", $b);
    
            list($aDate, $aTime) = explode(" ", $aExploded[substr_count($a, "|")]);
            list($bDate, $bTime) = explode(" ", $bExploded[substr_count($b, "|")]);
    
            if(strtotime("$aDate $aTime") == strtotime("$bDate $bTime"))
                return 0;
            return strtotime("$aDate $aTime") < strtotime("$bDate $bTime") ? 1 : -1;
    
        }
    
        function addEndLine($v) {
            return $v . PHP_EOL;
        }
    
        usort($lines, "timestampCmp");
    
        file_put_contents("test.txt", array_map("addEndLine", $lines));
    
    ?>
    

    【讨论】:

    • 我收到一个错误:解析错误:语法错误,第 5 行中的意外 T_FUNCTION ......
    • @Albance 不客气!祝你今天过得愉快! (顺便说一句:下次从一开始就包含您的代码!)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    相关资源
    最近更新 更多