我有一个文本文件,它包含公司名称和价格。像这样:
first company name
2,2
second company name
2,7
third company name
1,9
问题是我无法正确阅读和显示数据。我的代码:
<?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'];
}
?>
有什么问题?我还需要将数据发送到SQL数据库,但首先我必须澄清上面的代码。
答案 0 :(得分:4)
Beacuse file
函数返回行数组。并且你逐行循环,你应该按行对循环。你可以这样做:
$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
(
[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
)
)