0

我正在编写一个实用程序来从文本文件中加载一些数据。我有一个字典文件的集合,我正在处理成定义数据文件结构的数组。是的,我可以使用类或其他方式,但是使用数组,我被难住了。

假设我有 3 个文件可以读取并加载到数组中。当我读取数组时,尽管尝试使用 unset 和其他东西,但第三个实例具有第二个元素。我错过了什么?我在 cygwin 上使用 php 5.3.16

以下是列表的示例,但不是真正的列表。所以,请忽略 substr 语句,因为它们不是真实的

fname c 1 16
lname c 17 30

addr c 1 20
city c 21 30
state c 31 40
zip n 41 45

bday d 1 9
ssn c 10 18

当使用下面的代码加载时,第三个数组包含第二个数组的元素,即 bday、ssn、state 和 zip。

$cnt = 0;
while ($s = fgets($fp, 1024)) {
    $fldprops = array();
    $fldprops[0] = trim(substr($s,0,8));
    $fldprops[1] = trim(substr($s,9,1));
    $fldprops[2] = trim(substr($s,11,3));
    $fldprops[3] = trim(substr($s,15,3));
    $flds[$cnt] = $fldprops;
    $cnt++;
    unset($fldprops);
}

我曾认为 $fldprops = array(); 之一 或 unset() 将清除数组但它不起作用。

更新:我弄错了故障点。它显然不是在写入外部数组,而是在读取。正如我在评论中提到的,稍后在代码中,我有一个 foreach 循环,这里它失败了:

foreach ($flds as $fldprop) {
     var_dump($fldprop);
}

在这里,我得到 bday、ssn、state 和 zip(第二个数组的最后两个条目与第三个数组合并)。

4

2 回答 2

1

这是我得到的输出:

<?php
    $flds = array();
    $cnt = 0;
    $s = "HelloWorldNiceToSeeYou";
    $fldprops = array();
    $fldprops[0] = trim(substr($s,0,8));
    $fldprops[1] = trim(substr($s,9,1));
    $fldprops[2] = trim(substr($s,11,3));
    $fldprops[3] = trim(substr($s,15,3));
    $flds[$cnt] = $fldprops;
    $cnt++;
    unset($fldprops);
    var_dump($flds, $cnt, $fldprops);
?>

输出:

<br />
<b>Notice</b>:  Undefined variable: fldprops in <b>/code/MQpnac</b> on line <b>13</b><br />
array(1) {
  [0]=>
  array(4) {
    [0]=>
    string(8) "HelloWor"
    [1]=>
    string(1) "d"
    [2]=>
    string(3) "ice"
    [3]=>
    string(3) "oSe"
  }
}
int(1)
NULL

PHP Notice:  Undefined variable: fldprops in /code/MQpnac on line 13

所以 PHP 做得对。现场查看:http ://codepad.viper-7.com/MQpnac

于 2012-10-05T15:19:06.653 回答
0

为什么还要打扰临时变量?

$cnt = 0;
while ($s = fgets($fp, 1024)) {
    $flds[$cnt] = array(
        trim(substr($s,0,8)), 
        trim(substr($s,9,1)), 
        trim(substr($s,11,3)), 
        trim(substr($s,15,3)), 
    )
    $cnt++;
}
于 2012-10-05T15:27:40.697 回答