我把这个内容放在文件中:
12x4x11 12x17x20 4x19x30 5x18x10 17x6x18 19x30x20 11x2x17 30x13x19 22 x 23 x 7 17x28x2 5x17x30
当我逐行读取文件并使用模式'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";
}
数组看起来如何:
http://i.stack.imgur.com/OhLzQ.png
排序后:
您只需要删除数组的最后一个元素,然后再使用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";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句