从 PHP 中的数组键创建新变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4916510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create new variables from array keys in PHP
提问by Derek Maciel
Suppose I have an array, like this:
假设我有一个数组,如下所示:
$foo = array('first' => '1st',
'second' => '2nd',
'third' => '3rd');
How can I pick the keys out of the array and make them their own variables?
For example, the array $foo
would become:
如何从数组中挑选键并使它们成为自己的变量?例如,数组$foo
将变为:
$first = '1st';
$second = '2nd';
$third = '3rd';
I ask this because I am creating an MVC framework to help with my OOP, and I would like the user to pass a variable to the View loading function, which will allow the user to use variables in the template without having to know what the array was called.
我问这个是因为我正在创建一个 MVC 框架来帮助我的 OOP,我希望用户将一个变量传递给 View 加载函数,这将允许用户在模板中使用变量而不必知道数组是什么被称为。
For example:
例如:
$array = array('title' => 'My blog!' [...]);
$this->load->view('view.php', $array);
view.php:
视图.php:
echo $title;
Output:
输出:
My blog!
我的博客!
回答by KomarSerjio
<?php extract($array); ?>
回答by xil3
You could do this:
你可以这样做:
foreach($foo as $k => $v) {
$$k = $v;
}
回答by Hamish
A simple method is to use variable variables:
一个简单的方法是使用可变变量:
foreach($foo as $key => $value) {
$$key = $value;
}
echo $first; // '1st'
Note that this is generally discouraged however. It would be better to alter your templating system to allow for variables to be scoped within the template. Otherwise you could have issues with collisions and have to test for their existence, etc.
请注意,通常不鼓励这样做。最好更改您的模板系统以允许变量在模板内限定范围。否则,您可能会遇到碰撞问题,并且必须测试它们的存在等。
回答by Ingeborg
This is really an answer to my own question, but since it was marked as a duplicate, I was advisedto post my answer here. (I do not have the privilege to post in meta.)
这确实是我自己的问题的答案,但由于它被标记为重复,因此建议我在此处发布我的答案。(我没有在元中发帖的特权。)
When you have a table in a database with many columns, it can be an hassle to make a variable for each one. The great thing is that you can make variables automatically!
当数据库中有一个包含许多列的表时,为每一列创建一个变量可能会很麻烦。最棒的是你可以自动创建变量!
This method uses the heading / title / name of the columns in a database table as variable names, and the content of the selected row as the variables' value.
此方法使用数据库表中列的标题/标题/名称作为变量名称,并将所选行的内容作为变量值。
This approach is suitable when you only select onerow from the table. My code with comments:
这种方式适合当你只能选择一个从表行。我的代码与评论:
$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
Since I'm no pro the code might not be the best, but it works for me :-) When the list of the variables appeared on my web page I copied it into Excel and used concatenate to make php/html/css-code: paragraphs with designated class for each variable. Then I copied this code back into the code of my web page, and moved every piece around. Before finishing I commented out this line:
由于我不是专业人士,因此代码可能不是最好的,但它对我有用:-) 当我的网页上出现变量列表时,我将其复制到 Excel 中并使用 concatenate 制作 php/html/css-code :为每个变量指定类的段落。然后我将这段代码复制回我的网页代码中,并移动了每一部分。在完成之前,我注释掉了这一行:
//echo $kolonnetittel . "<br>";
Useful links:
有用的链接:
- W3 School on fetch_field
- PHP on fetch_field
- PHP on Extract
- W3 School on Extract
- Video tutorial: Inserting database results into array in PHP
I hope this '"tutorial" might help someone else!
我希望这个“教程”可以帮助别人!
回答by Supun Kavinda
In PHP 7.1, you can use the list() and it's shorthandto create new variable from array keys.
在 PHP 7.1 中,您可以使用list() 并且它是从数组键创建新变量的简写。
$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;
This gives you more control on pulling out variables from an array. For instance, you can pull out only 'first' and 'second' and skip other.
这使您可以更好地控制从数组中提取变量。例如,您可以仅提取“第一”和“第二”并跳过其他。