-1

我有一个文本文件,其中包含公司名称和价格。像这样:

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 数据库,但首先我必须澄清上面的代码。

4

1 回答 1

4

因为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
        )

)
于 2012-05-30T17:21:06.667 回答