使用php将多个换行符分解为多维数组
我有一个.txt文档设置如下:使用php将多个换行符分解为多维数组,php,arrays,multidimensional-array,text-files,flat-file,Php,Arrays,Multidimensional Array,Text Files,Flat File,我有一个.txt文档设置如下: HAYLE08 VALUE X VALUE Y BRUNO10 VALUE X VALUE Y Array ( [HAYLE08] => Array ( [0] => Value X [1] => Value Y ) [BRUNO10] => Array ( [0] => Value X
HAYLE08
VALUE X
VALUE Y
BRUNO10
VALUE X
VALUE Y
Array
(
[HAYLE08] => Array
(
[0] => Value X
[1] => Value Y
)
[BRUNO10] => Array
(
[0] => Value X
[1] => Value Y
)
)
$file = file_get_contents('test.txt');
$lines = explode( "\n\n", $file );
$lines = explode( "\n\n", $file );
$return = array();
foreach ($lines as $line) {
$items = explode("\n", $line);
$return[array_shift($items)] = $items;
}
print_r($return);
需要将其处理为如下多维数组:
HAYLE08
VALUE X
VALUE Y
BRUNO10
VALUE X
VALUE Y
Array
(
[HAYLE08] => Array
(
[0] => Value X
[1] => Value Y
)
[BRUNO10] => Array
(
[0] => Value X
[1] => Value Y
)
)
$file = file_get_contents('test.txt');
$lines = explode( "\n\n", $file );
$lines = explode( "\n\n", $file );
$return = array();
foreach ($lines as $line) {
$items = explode("\n", $line);
$return[array_shift($items)] = $items;
}
print_r($return);
将文件读入php没有问题,分解不同的3行代码块非常简单,如下所示:
HAYLE08
VALUE X
VALUE Y
BRUNO10
VALUE X
VALUE Y
Array
(
[HAYLE08] => Array
(
[0] => Value X
[1] => Value Y
)
[BRUNO10] => Array
(
[0] => Value X
[1] => Value Y
)
)
$file = file_get_contents('test.txt');
$lines = explode( "\n\n", $file );
$lines = explode( "\n\n", $file );
$return = array();
foreach ($lines as $line) {
$items = explode("\n", $line);
$return[array_shift($items)] = $items;
}
print_r($return);
当然,这只是我迈出的第一步:
Array
(
[0] => HAYLE08
VALUE X
VALUE Y
[1] => BRUNO10
VALUE X
VALUE Y
)
我尝试过不同的前肢和其他循环或线爆炸来填充其他维度,但都是徒劳的。我觉得问这样一个简单的问题有点愚蠢,但即使在研究之后,我似乎还是缺少一些基本的数组逻辑。
谢谢大家! 分解块后,必须循环新数组并将剩余字符串分解为它们自己的块
$tempArray = array( );
foreach( $lines as $line )
{
$chunks = explode( "\n", $line );
for( $i = 1; $i < sizeof( $chunks ); $i++ )
$tempArray[$chunks[0]][] = $chunks[$i];
}
$tempArray=array();
foreach($line作为$line)
{
$chunks=分解(“\n”,$line);
对于($i=1;$i
未经测试的PHP代码,但这应该适合您
$tempArray
将是您所需的阵列。您的阵列就快到了。您确实希望使用另一个循环/分解。大概是这样的:
HAYLE08
VALUE X
VALUE Y
BRUNO10
VALUE X
VALUE Y
Array
(
[HAYLE08] => Array
(
[0] => Value X
[1] => Value Y
)
[BRUNO10] => Array
(
[0] => Value X
[1] => Value Y
)
)
$file = file_get_contents('test.txt');
$lines = explode( "\n\n", $file );
$lines = explode( "\n\n", $file );
$return = array();
foreach ($lines as $line) {
$items = explode("\n", $line);
$return[array_shift($items)] = $items;
}
print_r($return);
虽然我稍微喜欢foreach解决方案,但这一个也很好地工作,所以谢谢!