为什么这个PHP代码不输出属性值?

时间:2011-05-16 22:17:19

标签: php debugging import foreach

我尝试在上传后导入制表符分隔文件。这是通过以下功能完成的。我正在尝试构建一个类实例数组。代码如下:

导入功能

$AddedProducts;
function importList($filename)
{
    global $AddedProducts;
    $AddedProducts=array();
    $fileHandle = fopen($filename, "r");
    $currentProduct = new productImport();

      $line=fgets($fileHandle); $line=fgets($fileHandle); //throw away top 2 lines
    echo '<hr>';
    while(true)
    {
        $line = fgets($fileHandle);
        if($line == null)   break;

        $cells=explode('    ', $line);
        $i=0;

        foreach($currentProduct as $ProductProperty)
        {
            if(isset($cells[$i]))
            {
                $ProductProperty = $cells[$i];
                echo $i . '. ' . $cells[$i] . "<br>";
            }
            else return false;
            $i++;
        }
        echo "<hr>";
        $AddedProducts[]=$currentProduct;
    }
    fclose($fileHandle);
    return true;
}

数组输出

<?  
$i=0;
foreach($AddedProducts as $AddedProduct)
{
    $i++;
    echo "<hr>" . $i . "<br>";
    foreach($AddedProduct as $key=>$value)
    {
        echo $key . ' = ' . $value . '<br>';
    }
}
?> 

已知信息细分

  • 最终的数组长度/大小是正确的。 (应该是文件中的行 - 2)

  • productImport 类中有多少属性并不特别重要,只要它等于正在读取的文件中每行的相同数量的选项卡。

  • importList 函数回显 $ cells [$ i] 的正确值,这些值与我在数组输出中缺少的值相同。

问题似乎是没有将值分配给属性或者没有读取属性。我不确定为什么会出现这种情况,但我认为这是因为PHP不是我的主要语言,而且可能是关于foreach循环的明显事实;)

我正在使用PHP v5.2.6

这段代码出了什么问题?

  

答案:

foreach($currentProduct as $ProductProperty) becomes
foreach($currentProduct as &$ProductProperty)

3 个答案:

答案 0 :(得分:1)

在foreach循环中,指定的变量(如$ProductProperty)不是引用,因此它们实际上不会影响循环外的任何内容。

即。 $ProductProperty = $cells[$i]仅影响当前的迭代。

答案 1 :(得分:1)

我认为问题在于本节:

foreach($currentProduct as $ProductProperty)
        {
            if(isset($cells[$i]))
            {
                $ProductProperty = $cells[$i];        /* this seems to be the problem */
                echo $i . '. ' . $cells[$i] . "<br>";
            }
            else return false;
            $i++;
        }

根据php manualUnless the array is referenced, foreach operates on a copy of the specified array and not the array itself.所以您分配的值会在循环后被丢弃。

编辑除此之外,您正在循环访问对象属性,虽然the manual没有明确说明它,但似乎您需要foreach($class as $key => $value)而不仅仅是{{1 }}

答案 2 :(得分:0)

除了其他人所说的内容之外,您似乎每次都尝试将属性数据插入同一个对象,因为您没有在循环中创建任何新的productImport实例。

相关问题