1

PDO sql codes :

while($r = $q->fetch(PDO::FETCH_ASSOC)){
    $gg = join('</td><td>', $r);
    echo "<tr><td>" . $no_count . "</td><td>" . $gg . "</td></tr>";
    $no_count = $no_count + 1;      
}

variable $r is the record, how can I echo the field name of $r?

Let's say $r carry records from 2 different fields "product" and "price". The value of $r is "apple", "130". How can I add "usd" into "130"?

I need something like.... if $field_name == "$r['price']" { $r = join('usd', $r); };

Thanks to Mike B, I almost there :

while($r = $q->fetch(PDO::FETCH_ASSOC)){
            foreach ($r as $name => $value) {
                if ($name == "price"){
                     $r = "usd" . $value; // this line got problem, how to change the value in an array variable $r?
                }
            }

            $gg = join('</td><td>', $r);
            echo "<tr><td>" . $no_count . "</td><td>" . $gg . "</td></tr>";
            $no_count = $no_count + 1;              
}
4

1 回答 1

3

array_keys($r)由于您正在获取关联数组,因此将为您提供表中的字段列表。

您还可以循环遍历$r

foreach ($r as $name => $value) {
  print "$name: " . $value;
}

更新

// 这行有问题,如何改变数组变量 $r 中的值?

$r[$name] = 'usd' . $value;

对原始名称进行编辑。由于您在$nameforeach 循环中的变量中有键,因此您可以直接设置它。

于 2012-06-04T21:47:51.380 回答