[英]Reading text file using PHP
I have a text file, and it contains company names and prices. 我有一个文本文件,其中包含公司名称和价格。 Like this: 像这样:
first company name
2,2
second company name
2,7
third company name
1,9
The problem is that I can't read and show data properly. 问题是我无法正确读取和显示数据。 My code: 我的代码:
<?php
$content=file("test_data.txt");
foreach ($content as $data)
{
$data = array(
'company' => $content[0],
'price' => $content[1]
);
echo $data['company'];
echo "<br>";
echo $data['price'];
}
?>
What is wrong? 怎么了? I need also to send data to SQL database, but first I would have to clarify the code above. 我还需要将数据发送到SQL数据库,但是首先我必须澄清上面的代码。
Beacuse file
function returns array of lines. 因为file
功能返回行数组。 And you loop lien by line, you should loop file by line-pairs. 而且您逐行循环留置权,您应该按行对循环文件。 You can do it like this: 您可以这样做:
$lines = file("test_data.txt");
$data = array();
for($i = 0; $i < count($lines); $i += 2)
{
$pair = array();
$pair['company'] = $lines[$i];
$pair['price'] = $lines[$i + 1];
$data[] = $pair;
}
$data
array should look similar to: $data
数组应类似于:
Array
(
[0] => Array
(
[company] => first company name
[price] => 2,2
)
[1] => Array
(
[company] => second company name
[price] => 2,7
)
[2] => Array
(
[company] => third company name
[price] => 1,9
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.