donglei1699
donglei1699
2012-01-04 01:58

PHP变量for循环

已采纳

hey guys is this even possible to be done in php

<?php   
$sectorcount = $row_SectorCount['COUNT(*)'];
//number of rows in database
for ($i = 1; $i <= $sectorcount; $i++)
{
${spendingname . $i}= array();
${spendingpercent . $i} = array();
${spendingid . $i} = array();

mysql_select_db($database_conn2, $conn2);
$query_Spending = "SELECT CONCAT(spending.SectorID, spending.ExpenditureID) AS 'SpendingID',
expenditure.ExpenditureName, spending.SpendingPercent, spending.SectorID
FROM spending   
INNER JOIN expenditure ON spending.ExpenditureID = expenditure.ExpenditureID
WHERE spending.SectorID = ".$i;
$Spending = mysql_query($query_Spending, $conn2) or die(mysql_error());
$totalRows_Spending = mysql_num_rows($Spending);
while($row_Spending = mysql_fetch_assoc($Spending))
{
${spendingname.$i}[] = $row_Spending['ExpenditureName'];
${spendingpercent.$i}[] = $row_Spending['SpendingPercent'];
${spendingid.$i}[]= $row_Spending['SpendingID'];
}
mysql_free_result($Spending);
}

i was planning to use this here in this context. having an array to draw out the values using a where clause and display them individually

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

5条回答

  • drsqpko5286 drsqpko5286 9年前

    This is what you are looking for:

    for ($i = 0; $i < 14; $i++) {
        ${'name' . $i} = $i;
    }
    
    echo $name3;
    

    But you should just use an array:

    $name = array();
    for ($i = 0; $i < 14; $i++) {
        $name[$i] = $i;
    }
    
    echo $name[3];
    

    If you need an array in an array, go ahead and do that too. If you need more nested arrays than that, you should probably be using a class somehow instead of all that array nesting.

    点赞 评论 复制链接分享
  • duannei1477 duannei1477 9年前

    It will not give desired output 1 instead will give 13

    What s the reason of doing like this. you can make array a access is later on use

     for($i=0; $i<=13; $i++)
     {
            $name[$i]=$i;
     }
    
          echo $name[1];                    *//it will echo 1
    
    点赞 评论 复制链接分享
  • douxie9471 douxie9471 9年前

    As Kolink said, that is what an array is for!

    However, What you are asking can be achieved:

    Read More Here

    Basically,

    <?php
    
    for($i=0; $i<=13; $i++){
    
        $varname = "name" . $i;
        $$varname=$i;
    
    }
    
    echo $name1; // 1
    
    ?>
    
    点赞 评论 复制链接分享
  • douke6027 douke6027 9年前

    First off, I second the suggestion to use an array instead. Variable variables are not meant to be used like this.

    That said, it is possible by accessing ${$name.$i}, or perhaps doing something like

    $varname = $name.$i;
    $$varname = 1; // or read from $$varname
    
    点赞 评论 复制链接分享
  • dongpao1918 dongpao1918 9年前

    Use an array. That's what they're there for.

    点赞 评论 复制链接分享

相关推荐