我有多个键和一个数组,一次只存在一个键,但我不知道哪个键存在。
我的问题是我必须获得数组中存在的那个键的值,但我不想在个别键上使用loop
或isset
,我想知道是否有任何存在内置PHP函数,我可以通过它实现此解决方案吗?
$keys = array("key1","key2","key3");
$data= array("mykey"=>"myval","mykey2"=>"myval2","key2"=>"key2val");
$val = isset($data["key1"])?1:(isset($data["key2"])?2:(isset($data["key3"])?3:0));//i dont want to use this or any loop
答案 0 :(得分:2)
以下是您的解决方案:
$keys = array("key1","key2","key3");
$data= array("mykey"=>"myval","mykey2"=>"myval2","key2"=>"key2val");
print_r (current(array_intersect_key($data, array_flip($keys))));
我认为你需要使用循环,因为这将是一个更好的解决方案
$keys = array("key1","key2","key3");
$data= array("mykey"=>"myval","mykey2"=>"myval2","key2"=>"key2val");
foreach($data as $key=>$value)
{
if(in_array($key,$keys))
{
// your logic
}
}
答案 1 :(得分:2)
走他们的路口:
// Flip is needed for [key1 => 0, ...] representation
$list = array_intersect_key(array_flip($keys), $data);
// Check existence
if ($list) {
// You need the value, started from 1 (instead of zero)
$val = 1 + current($list);
} else {
$val = 0;
}
答案 2 :(得分:1)
这是一个班轮。但是你能在一个月后解释一下吗?
$keys = array("key1","key2","key3");
$data = array("mykey"=>"myval","mykey2"=>"myval2","key2"=>"key2val");
print_r( array_intersect($keys, array_keys($data)) );
// Output:
Array
(
[1] => key2
)