用php将多个换行符分解为多维数组
我有一个像这样设置的 .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
[1] => Value Y
)
)
将文件读入 php 是没有问题的,并且分解 3 行的不同块非常容易,如下所示:
$file = file_get_contents('test.txt');
$lines = explode( "\n\n", $file );
但是当然,这只会给我第一步:
Array
(
[0] => HAYLE08
VALUE X
VALUE Y
[1] => BRUNO10
VALUE X
VALUE Y
)
我尝试了不同的 foreach 和其他循环或线爆炸来填充其他维度,但一切都是徒劳的。我觉得问这样一个简单的问题有点愚蠢,但即使经过研究,我似乎还是缺少一些基本的数组逻辑。 谢谢你!
I have a .txt document set up like this:
HAYLE08
VALUE X
VALUE Y
BRUNO10
VALUE X
VALUE Y
Which needs to processed to a multidimensional array like this:
Array
(
[HAYLE08] => Array
(
[0] => Value X
[1] => Value Y
)
[BRUNO10] => Array
(
[0] => Value X
[1] => Value Y
)
)
Reading the file into php is no problem and exploding the different chunks of 3-lines is very easy like this:
$file = file_get_contents('test.txt');
$lines = explode( "\n\n", $file );
But of course, this will only give me the first step:
Array
(
[0] => HAYLE08
VALUE X
VALUE Y
[1] => BRUNO10
VALUE X
VALUE Y
)
I've tried different foreaches and other loops or line explodes to populate the other dimensions, yet all in vain. I feel kind of stupid to ask such a simple question, but even after researching I just seem to be missing some basic array-logic here.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你快到了。您确实想使用另一个循环/爆炸。像这样的事情:
Your almost there. You do want to use another loop / explode. Something like this:
分解块后,您必须循环遍历新数组并将剩余的字符串分解为它们自己的块。
未经测试的 PHP 代码,但这应该适合您。
$tempArray
将是您想要的数组。After exploding the chunks, you'll have to loop through the new array and explode the remaining strings into their own chunks.
Untested PHP code, but that should work for you.
$tempArray
will be the array you want.