php 将数组拆分为php中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8420103/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:39:41  来源:igfitidea点击:

Splitting an array into the variables in php

phparraysvariablessplit

提问by sujitrulz

I have this array, $display_vars, and I want to split it into separate variables, so each variable's name is the array key, and it's value is the value, so to speak. So if the array was like this:

我有这个数组 $display_vars,我想把它拆分成单独的变量,所以每个变量的名称是数组键,它的值是值,可以这么说。所以如果数组是这样的:

$display_vars = array(
'title' => 'something',
'header' => 'something else'
);

Then I want to end up with the equivalent of this:

然后我想以这样的方式结束:

$title = 'something';
$header = 'something else';

Can you think of any way I can possibly do this?

你能想出我有什么办法可以做到这一点吗?

回答by Jon

The extractfunction does exactly this.

extract函数正是这样做的。

See it in action(includes bonus reference to get_defined_vars).

看到它在行动(包括奖金参考get_defined_vars)。

回答by Jason McCreary

extract()

extract()

Be mindful about overwriting variables of the same name in the current scope. Read up on the second parameter if this is a concern.

注意覆盖当前作用域中的同名变量。如果这是一个问题,请阅读第二个参数。

回答by Shankar Damodaran

Why don't you use just access it using the same array ? Calling a function like extractis just an overload.

为什么不使用仅使用相同的数组访问它?调用像这样的函数extract只是一个重载。

<?php
$display_vars = array(
'title' => 'something',
'header' => 'something else'
);

echo $display_vars['title']; //something
echo $display_vars['header']; //something else