【问题标题】:set array's elements as independent variables将数组的元素设置为自变量
【发布时间】:2019-03-07 19:04:10
【问题描述】:

我正在寻找一个 php 函数,它将数组的元素设置为自变量(同名)

我在下面编写了应该可以解决问题的代码... 在 php 中是否已经有任何功能可以做到这一点?

$data = array(...);

foreach ($data as $key => $value) {
 ${$key} = $value;
}

【问题讨论】:

标签: php arrays variable-assignment


【解决方案1】:

您正在寻找 PHP extract():

extract($data);

http://php.net/manual/en/function.extract.php

【讨论】:

    【解决方案2】:

    试试

    $info = array('coffee', 'brown', 'caffeine');
    
    // Listing all the variables
    list($drink, $color, $power) = $info;
    
    echo "$drink is $color and $power makes it special.\n";
    

    或者

    foreach($ARRAY as $key=>$value) { 
        $$key = $value; 
    }
    

    【讨论】:

    • 感谢您的回答,但您的第一个脚本假设我知道元素是什么,您的第二个脚本是我自己到达的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 2016-01-20
    • 1970-01-01
    相关资源
    最近更新 更多