在拆分数组中的额外值之后


php, after split extra value in array

我在文件中放入了这个内容:

<>之前12 x4x1112 x17x204 x19x305 x18x1017 x6x1819 x30x2011 x2x1730 x13x1922 x23x717 x28x25 x17x30之前

当我逐行读取文件并使用模式'x'拆分行时,数组总是在数组中添加额外的空间,因此排序数组不正确。这里的代码:

$array = array();
$handle = fopen("2.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $line = split('x', $line);
        //sort($line);
        print_r($line);
        array_push($array, $line);
    }
    fclose($handle);
} else {
    echo "File is failed to open";
} 

How is looking array:

https://i.stack.imgur.com/OhLzQ.png

排序后:

https://i.stack.imgur.com/4t4V4.png

你的问题是新行是你所读行的一部分。比如这一行

12 x4x11

11的值实际上是11/n

/n是新的行字符。

解决这个问题的方法很简单,只要在分割前读取该行时修剪该行即可。这应该会删除新行char

这样的

$line = split('x', trim($line));

您只需要在使用array_pop函数将数组的最后一个元素放入数组之前删除它:

PHP

$array = array();
$handle = fopen("2.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $line = split('x', $line);
        array_pop($line);
        //sort($line);
        print_r($line);
        array_push($array, $line);
    }
    fclose($handle);
} else {
    echo "File is failed to open";
} 

或者你可以使用PHP的trim函数来删除行尾的空格:

PHP

$array = array();
$handle = fopen("2.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $line = split('x', trim($line));
        //sort($line);
        print_r($line);
        array_push($array, $line);
    }
    fclose($handle);
} else {
    echo "File is failed to open";
}