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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?