简体   繁体   English

PHP从数组获取键值

[英]PHP get key value from array

When I put print_r($data); 当我把print_r($data); I get the following 我得到以下

Array
(
    [name] => Cheese
)

Is there a way to get the key name in a variable on its own? 有没有办法自己获取变量中的键name

There may be occasions that name could be email and other values. 在某些情况下, name可能是email和其他值。

Use array_keys() : 使用array_keys()

var_dump(array_keys($data));

Return all the keys or a subset of the keys of an array 返回数组的所有键或键的子集

Do you mean you know the value but you don't know the key? 您是说您知道价值,但您不知道钥匙吗? If so you could write something like this: 如果是这样,您可以这样写:

$array = ['name' => 'Cheese'];
array_flip($array);
var_export($array['Cheese']); // Output: name

You can have the array key extracted to their own variables using the extract function. 您可以使用extract函数将数组键提取到自己的变量中。 For example 例如

$a = array("color"=>"blue");
extract($a);
echo $color; 

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

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