dongtang1966 2015-07-30 16:19
浏览 38
已采纳

调用函数时,php extract()关联数组

I have this function:

function extractAvailable($assoc1, $assoc2){
    if($assoc1) extract($assoc1);
    else extract($assoc2);
}

What I expect is to call this function later in the global scope, and have my variables available, like so:

$arr1 = [];
$arr2 = ['one'=>1, 'two'=>'SecondItem'];
extractAvailable($arr1, $arr2);

With the call on extractAvailable(), I need to have the varialbes $one and $two available in the current scope. Obviously, I've got something wrongly figured concerning variable scope use here, 'cause it isn't working. When I try to use the variable, what I get instead is Notice: Undefined variable: one.

How do I get this to work?

  • 写回答

2条回答 默认 最新

  • 普通网友 2015-07-30 16:29
    关注

    If you want them to be available in the global scope, you can use variable variables instead of extract, and specify them as global.

    function extractAvailable($assoc1, $assoc2){
        if($assoc1) {
            foreach ($assoc1 as $key => $value) {
                global $$key;
                $$key = $value;            
            }
        } else {
            foreach ($assoc2 as $key => $value) {
                global $$key;
                $$key = $value;            
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)