0

I have a feeling I'm going to get scolded for this but here is the question.

$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number) 
{
    Bullet <?php echo $seq_number;?>  
    // (this successfully creates - Bullet 1, Bullet 2, etc. - 
        below is the problem.

    <?php echo $db_rs['bullet_($seqnumber)'];?>
}   // this one doesn't work.  

I've tried with curly brackets {}

I basically have a few columns that are named same except for number at the end (bullet_1, bullet_2, bullet_3, etc.) and want to get the results using a loop.

4

4 回答 4

5

Your problem is, that PHP doesn't replace variables inside strings enclosed with single quotes. You need to use $db_rs["bullet_{$seq_number}"] or one of those:

<?php
foreach ($seq_numbers as $seq_number) {
   $key = 'bullet_' . $seq_number;
   echo $db_rs[$key];
}

Even shorter, but a little less clear:

<?php
foreach ($seq_numbers as $seq_number) {
   echo $db_rs['bullet_' . $seq_number];
}

An entirely different approach would be to loop over the result array. Then you don't even need $seq_numbers. Just as an afterthought.

<?php
foreach ($db_rs as $key => $value) {
   if (substr($key, 0, 7) == 'bullet_') {
      echo $value;
   }
}

Oh...and watch out for how you spell your variables. You are using $seq_number and $seqnumber.

于 2013-01-18T08:29:20.383 回答
1

为什么不:

$db_rs['bullet_'.$seqnumber]

如果没有,你的字段是什么,$db_rs 的 var_dump 是什么样的?

于 2013-01-18T08:31:57.853 回答
1
<?php echo $db_rs['bullet_'.$seqnumber];?>
于 2013-01-18T08:29:23.940 回答
0

尝试这个...

$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number) 
{
    Bullet <?php echo $seq_number;?>  
    // (this successfully creates - Bullet 1, Bullet 2, etc. - 
        below is the problem.

    <?php echo $db_rs["bullet_($seqnumber)"];?>
}   // now it works.
于 2013-01-18T08:41:17.203 回答