duanhuilao0787 2014-03-20 10:27 采纳率: 100%
浏览 108
已采纳

foreach循环中的PHP变量变量不起作用

This is a brilliant little trick if I can get it to work - I have hundreds data columns from dozens of tables spread across a dozen data forms (they are HTML print forms) and they are all html with embedded php variables. Very normal. However the customer had a requirement to know what field went in where - a very good question.

So what did I do? I worked on a solution that allows the key'd arrays from the database to give up their column names. a brilliant move! except I need to do it via variable variables, and guess what, they DON'T work in a foreach loop.

here is the code

   if ($_REQUEST['data']=="false"){
        $supera = array("RowService", "RowSite", "RowCustomer", "RowEngineer"); //there can be many of these they are key'd arrays $RowService['column_name_1']; is the format
        foreach($supera as $super){
            foreach(${$super} as $key=>$value){
                if (!is_numeric($key)){
                    ${$super}[$key] = "<span style=\"color:pink;\">".$key."</span>";
                }
            }
        }
    }

as you can see I want a kill switch easy mechanism to cut and paste the key'd arrays that aren't to show real data any more rather they are to show (in pink) the column name, and (perhaps) the table name too. There is a lot of code already in place and this would be a brilliant option if it can be made to work

EDIT: this is the PHP error:

 Warning: Invalid argument supplied for foreach()

EDIT: THE CODE ACTUALLY ALREADY WORKS: FIX IS TO test for is_array()

 if(is_array(${$super})) foreach(${$super} as $key=>$value){

will work, as opposed to just

 foreach(${$super} as $key=>$value){
  • 写回答

3条回答 默认 最新

  • dongpian6319 2014-03-20 10:38
    关注

    I'm not sure what you are trying to achieve but your code (simplified) works just fine:

    $a = array("asd", "qwe");
    $asd = array("a" => 1, "b" => 2, "c" => 3);
    $qwe = array("d" => 4, "e" => 5, "f" => 6);
    
    foreach ($a as $item)
    {
        foreach ($$item as $key => $value)
        {
            echo $key . ": " . $value . "<br />";
        }
    }
    

    Output:

    a: 1
    b: 2
    c: 3
    d: 4
    e: 5
    f: 6
    

    Most likely one of your variables is empty (not an array) and that's why you receive that warning.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数