简体   繁体   English

使用PHP将数组中的每个元素分配给变量。

[英]Assign each element in an array to a variable using PHP.

I have an array with unknown information. 我有一个包含未知信息的数组。 I want to get each element and assign it to a variable so I can use it elsewhere. 我想获取每个元素并将其分配给变量,以便我可以在其他地方使用它。

This works but it only gets the first element. 这有效,但它只获得第一个元素。

function firstElement($foo,$m='k') {
                    foreach ($foo as $k=>$v){
                    return $$m;
                }
}

$firstKey=firstElement($foo);
$firstVal=firstElement($foo,'v');

You could use the extract() PHP function. 你可以使用extract()PHP函数。 If you want to doit yourself: 如果你想自己做:

Remove the "return" statement from there. 从那里删除“return”语句。 Once you "return" a value, the foreach and the entire functions stops. 一旦你“返回”一个值,foreach和整个函数就会停止。

The extract() function will pull out each array key and assign the value to a variable. extract()函数将拉出每个数组键并将值赋给变量。 If the key is, for example, 'color', then it will name the new variable $color and assign the value from the array key to it. 如果键是“颜色”,那么它将命名新变量$ color并将数组键中的值赋给它。

extract($foo);

Answering my own question: 回答我自己的问题:

To find out what the name was assigned to each element I used print_r($foo); 为了找出为每个元素分配的名称,我使用了print_r($ foo);

This gave me: 这给了我:

array("a" => "blah", "b" => "blah")

Then I used extract 然后我用了提取物

extract($foo);

//echo "$a";
//echo "$b";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM