为什么最后一个数组列看起来像这样?
问题描述:
使用文件与此内容:为什么最后一个数组列看起来像这样?
1 2 3 4 5 0
6 7 8 9 10 0
11 12 13 14 15 1
16 17 18 19 20 1
我试试这个代码来创建二维数组并获得最后一列:
<?php
$tab = array();
$lastColumn=array();
$file = file('test.txt');
foreach ($file as $item) {
array_push($tab, explode(' ', $item));
};
foreach ($tab as $item) {
array_push($lastColumn,end($item));
};
var_dump($lastColumn);
但去年cloumn看起来是这样的:
array(4) { [0]=> string(3) "0 " [1]=> string(3) "0 " [2]=> string(3) "1 " [3]=> string(1) "1" }
所有除了最后一个字符串(字符串(1)和后面没有空格)之后,值具有字符串(3)和空格
我需要在最后一列没有空格和字符串(1)的所有值。有人可以帮助我吗?
答
\n
表示的文件中有需要删除的换行符。
尝试改变:
foreach ($file as $item) {
array_push($tab, explode(' ', $item));
};
喜欢的东西:你所描述
foreach ($file as $item) {
array_push($tab, explode(' ', str_replace('\n','',$item)));
};
答
一切通常被称为编程whitespace。也就是说,字符串中存在的字符与字符的方式不可见。
PHP有一个内置的函数处理这个叫trim()
其中包括所有这些字符:
该函数返回空白的字符串从 剥离开始,海峡结束。如果没有第二个参数,trim()将 去掉这些字符:
“”(ASCII 32(0x20)),一个普通的空格。
“\ t”(ASCII 9(0x09)),一个选项卡。
“\ n”(ASCII 10(0x0A)),换行(换行)。
“\ r”(ASCII 13 (0x0D)),回车符。
“\ 0”(ASCII 0(0x00)),NUL字节。 “\ x0B”(ASCII 11(0x0B)),一个垂直标签。
所以
foreach ($tab as $item) {
array_push($lastColumn,end($item));
};
变为:
foreach ($tab as $item) {
array_push($lastColumn,end(trim($item)));
};
你是不是删除换行符并不能看到他们,但他们在那里 – charlietfl
我该怎么办呢? – Marcin
删除每行上的'\ n',然后爆炸 – charlietfl