0

我知道这个错误已经发生了很多,但是我无法在网站上找到另一个与我的问题相符的问题。

这是我的代码:

<?php

$handle = fopen('text document here', 'r');

if ($handle === false) {
die("ERROR");
}
$array = array();
$array = fgets($handle);

$handle = explode("\n", $array);

$foo = $handle;
$outA = array();
$outB = array();


foreach($foo as $value)
{
    list($x, $y) = explode(",",$value);
    $outA[] = $x;
    $outB[] = $y;
}

echo $outA[0];
echo $outB[0];
?>

我不断收到错误“注意:未定义的偏移量:第 20 行 C:\wamp\www\arraytest.php 中的 1”

虽然我得到了错误,但我从数组中打印了前两个值,它们似乎都是正确的,所以我不知道究竟是什么原因造成的。

- 编辑 -

这是我要导入的数据的结构:

12,13
12,14
12,15
12,16
12,17
12,18
12,21
12,22
12,31

4

1 回答 1

0

这里的问题是您实际上并没有遍历文件中的所有行。

$array = fgets($handle);

现在,$array变量将只包含第一行。其余行被忽略。

而且,在您的代码中,您有:

list($x, $y) = explode(",",$value);

它基本上试图将第一个数组值分配$x$y. 没有第二项,所以你会得到一个Undefined offset错误。

解决方案是实际循环遍历这些行。我会使用while如下循环:

$handle = fopen('text document here', 'r');

if ($handle === false) {
die("ERROR");
}

while(!feof($handle))
{
    $value = fgets($handle);
    list($x, $y) = explode(",",$value);
    $outA[] = $x;
    $outB[] = $y;
}

echo $outA[0]."\n";
echo $outB[0];

输出:

12
13 

其余的值也被正确存储。您可以使用print_r($outA);.

于 2013-09-07T19:13:10.893 回答