douliu1092 2015-08-27 01:04
浏览 41
已采纳

Foreach循环声明不同的变量取决于select列

Ref : Foreach loop declare variable on select table array

OK ..... No more syntax error

Same question

  • Is it possible to create variable inside foreach loop that each variable name depend on column name that I select?

I've coded out like

$recid = $_GET['recid'];
//sql select string declaration
$sql = "select [Rec_ID],[Bike_ID],[Station],['Line']
        from [rfttest].[dbo].[RFT_Records_Log]
        where [Rec_ID] = {$recid}";
$query = sqlsrv_query($conn,$sql); //query
//if query fail print out error
if($query === false)
{
    die(print_r(sqlsrv_errors(),true));
    sqlsrv_close($conn);
}
//continue with fetch array
$recdata = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC);
//foreach to declare variable
foreach($recdata as $x => $a)
{
    $"$x" = $"$a";
}

Result should be

$Rec_ID = row rec_id data , 
$Bike_ID = row bike_id data, 
$Station = row station data, 
$Line = row line data

but i get these instead

$row rec_id data = row rec_id data , 
$row bike_id data = row bike_id data, 
$row station data = row station data, 
$row line data = row line data
  • 写回答

1条回答 默认 最新

  • douduiwei2831 2015-08-27 01:14
    关注

    You have two options.

    One (the more secure one) is to use list():

    list($Rec_ID, $Bike_ID, $Station, $Line) = $recdata;
    

    This means that variable names can't overwrite variables by accident.

    Two (the less secure one) is to use extract()

    extract($recdata);
    

    This turns an associative array into a number of variables, but by default will overwrite any variables with the same names that are set. This is the closest to what you're trying to do currently.

    You can also pass a flag to extract to tell it not to overwrite existing variables (or to do a number of other things when there's a conflict).

    extract($recdata, EXTR_SKIP);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样