[英]Get array value with specific key format in PHP
Consider following array and function: 考虑以下数组和函数:
$array = [
'key' => [
'key_2' => [
'key_3' => 'Value 3'
]
],
];
function get_value( $key ) {
echo $array . $key;
}
now I want to call the function like this: 现在我想这样调用函数:
get_value( 'key[key_2][key_3]' );
It gives error which is natural. 它给出了自然的错误。
Possible to write get_value
function in a way that it understands 'key[key_2][key_3]'
and gives the value? 可以以理解
'key[key_2][key_3]'
并给出值的方式编写get_value
函数吗?
Since the input string seems to be used quite loosely I'm going to assume this can be manipulated to something easier to use. 由于输入字符串似乎非常宽松地使用,因此我将假定可以将其操纵为更易于使用的东西。
Here I explode the keys and loop them and dig in the array til I'm out of keys. 在这里,我将键分解并循环,直到没有键时才在数组中进行挖掘。
Mind that the return can be either array or string/int/float/bool 注意返回值可以是数组,也可以是string / int / float / bool
function get_value($array, $key ) {
$keys = explode(",", $key);
Foreach($keys as $k){
$array = $array[$k];
}
Return $array;
}
Var_dump(get_value($array, 'key,key_2,key_3' ));
https://3v4l.org/mnvOs https://3v4l.org/mnvOs
You can use the input string you have with a str_replace. 您可以将输入字符串与str_replace一起使用。
But I don't understand the logic in it. 但是我不明白其中的逻辑。 They are all keys, but only the second and third have
[]
around them. 它们都是键,但是只有第二个和第三个具有
[]
。
See here for str_replace example: https://3v4l.org/BObTk 请参阅此处以获取str_replace示例: https : //3v4l.org/BObTk
You cannot pass the argument to the function as mentioned in your code. 您不能如代码中所述将参数传递给函数。 If you want to print all the values or print a value of a specific key, you'll have to pass the key to the function as a string.
如果要打印所有值或打印特定键的值,则必须将键作为字符串传递给函数。
Consider the example below: 考虑下面的示例:
function get_value( $key = null ) {
$array = [
'key' => [
'key_2' => array(
'key_3' => 'Value 3'
)
],
];
$keys = explode('|', $key);
$result = '';
foreach ($keys as $key) {
if (empty($result)) {
$result = $array[$key];
} else {
$result = $result[$key];
}
}
echo $result;
}
Now if you pass get_value('key|key_2|key_3'), this will work. 现在,如果您传递get_value('key | key_2 | key_3'),则可以使用。
Also the scope in php is not as same as in javascript. 另外,php中的作用域与javascript中的作用域不同。 you cannot access the outside function variables inside a function.
您不能访问函数内部的外部函数变量。 Refer this article for more info on scopes Variable Scopes
请参阅本文以获取有关范围的更多信息可变范围
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.