在php中执行此操作的最佳方式

时间:2011-02-07 12:11:40

标签: php

我从数据库中获取数据,假设表中有23列,那么我必须编写23行来设置值。 还有其他简短的方法吗?

在下面的示例中,只有15列,我写了15行。任何简短的方式?

while( $row = mysql_fetch_array( $export ) )
    {
        $line = '';
        $line.=setValue($row[0]);
        $line.=setValue($row[1]);
        $line.=setValue($row[2]);
        $line.=setValue($row[3]);
        $line.=setValue($row[4]);
        $line.=setValue($row[5]);
        $line.=setValue($row[6]);
        $line.=setValue($row[7]);
        $line.=setValue($row[8]);
        $line.=setValue($row[9]);
        $line.=setValue($row[10]);
        $line.=setValue($row[11]);
        $line.=setValue($row[12]);
        $line.=setValue($row[13]);
        $line.=setValue($row[14]);

    }

4 个答案:

答案 0 :(得分:6)

while( $row = mysql_fetch_array( $export ) )
{
    $line = '';
    foreach($row as $value) {
        $line.=setValue($value);
    }
}

答案 1 :(得分:0)

我不确定这是否是您正在寻找的,但您可以使用这样的for循环:

while( $row = mysql_fetch_array( $export ) )
    {
        $line = '';
        for($i = 0; $i < 15; $i++)
        {
           $line.=setValue($row[$i]);
        }

    }

答案 2 :(得分:0)

while( $row = mysql_fetch_array( $export ) )
    {
        $line = '';
        for($i = 0; $i < 15; $i++) {
           $line .= setValue($row[$i]);
        }

    }

这是一种方法。还有其他人。您可以使用返回数组的计数替换“15”。这样,for循环将迭代直到数组结束。

Ups,哈哈,太晚了......

答案 3 :(得分:0)

虽然你可以做类似......

while ($row=mysql_fetch_array($export)) {
   $line=array();
   $line=array_map('setValue',$xport);
   $line=implode('',$line);
}

....它是一个非常混乱的构造 - 它预先假定查询将返回一个非常明确定义的结果集,并且结果集的结构及其后续应用程序是diplaced;作为一般经验法则,你永远不应该使用mysql_fetch_array - 改为使用mysql_fetch_assoc。

相关问题