【问题标题】:Create new variables from array keys in PHP在 PHP 中从数组键创建新变量
【发布时间】:2011-06-22 10:30:09
【问题描述】:

假设我有一个数组,像这样:

$foo = array('first' =>  '1st',
             'second' => '2nd',
             'third' =>  '3rd');

如何从数组中选择键并将它们设为自己的变量? 例如,数组$foo 将变为:

$first = '1st';
$second = '2nd';
$third = '3rd';

我问这个是因为我正在创建一个 MVC 框架来帮助我的 OOP,我希望用户将一个变量传递给视图加载函数,这将允许用户在模板中使用变量而无需知道数组叫什么。

例如:

$array = array('title' =>  'My blog!' [...]);
$this->load->view('view.php', $array);

view.php:

echo $title;

输出:

我的博客!

【问题讨论】:

  • P.S.示例来自codeIgniter 对
  • 这与问题无关。在其他一些情况下,如果您有较小的具有相同顺序的值数组,您还可以通过 list() 分配它们,这对 IDE 更友好。 $info = array('coffee', 'brown', 'caffeine'); list($drink, $color, $power) = $info;
  • 用新变量中的冗余数据使全局范围膨胀并没有真正的好处。只需在您想使用$title 的每个地方使用$array['title']。使用extract() 或可变变量通常表示编码设计欠佳。当这些技术对您的代码有吸引力时,通常是重新考虑的时候了。

标签: php arrays variables


【解决方案1】:

在 PHP 7.1 中,您可以使用 list() and it's shorthand 从数组键创建新变量。

$foo = array('first' =>  '1st',
             'second' => '2nd',
             'third' =>  '3rd');
list('first' => $first, 'second' => $second, 'third' => $third) = $foo;
// $first = '1st'

// or use shorthand
['first' => $first, 'second' => $second, 'third' => $third] = $foo;

这使您可以更好地控制从数组中提取变量。例如,您可以只拉出“第一”和“第二”并跳过其他。

【讨论】:

    【解决方案2】:

    这确实是对my own question 的回答,但由于它被标记为重复,I was advised 在此处发布我的回答。 (我无权在 meta 中发帖。)

    当您在数据库中有一个包含许多列的表时,为每个列创建一个变量可能会很麻烦。最棒的是你可以自动生成变量!

    此方法使用数据库表中列的标题/标题/名称作为变量名,并将所选行的内容作为变量的值。

    当您只从表中选择 一个 行时,此方法适用。我的 cmets 代码:

    $query = "SELECT * FROM mdlm WHERE mdlmnr = $id";  // Select only *one* row, the column mdlmnr is a unique key
    $resultat = $conn->query($query); //Get the result (the connection is established earlier)
    
    while ($col = $resultat->fetch_field()) { //fetch information about the columns
        $kolonnetittel = $col->name; //Set the variable as the name of the column
        echo $kolonnetittel . "<br>"; //Show all the column names/variables
    }
    
    $innhold = $resultat->fetch_assoc(); // get the content of the selected row as an array (not a multidimensional array!) 
    extract($innhold, EXTR_PREFIX_SAME, "wddx"); // Extract the array
    

    由于我不是专业人士,因此代码可能不是最好的,但它对我有用 :-) 当变量列表出现在我的网页上时,我将其复制到 Excel 中并使用连接来制作 php/html/ css-code:为每个变量指定类的段落。然后我将这段代码复制回我的网页代码中,并移动了每一块。在完成之前,我注释掉了这一行:

    //echo $kolonnetittel . "<br>"; 
    

    有用的链接:

    我希望这个“教程”可以帮助其他人!

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        一个简单的方法是使用变量变量:

        foreach($foo as $key => $value) {
           $$key = $value;
        }
        
        echo $first; // '1st'
        

        请注意,通常不鼓励这样做。最好更改您的模板系统以允许在模板内限定变量。否则,您可能会遇到碰撞问题,并且必须测试它们的存在等。

        【讨论】:

          【解决方案5】:

          你可以这样做:

          foreach($foo as $k => $v) {
            $$k = $v;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-09-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多