我有像这样的数组数据
library(ggplot2)
library(directlabels)
## Data
set.seed(10)
d <- data.frame(x=seq(1,100,1), y=rnorm(100, 3, 0.5))
d$z <- ifelse(d$y>3,1,0)
## Plot
p <- ggplot(d, aes(x=x, y=y, colour=as.factor(z))) +
stat_smooth(inherit.aes=T, se=F, span=0.8, show.legend = T) +
geom_line(colour="grey50") +
scale_x_continuous(limits=c(0,110)) +
geom_dl(label="text", method="maxvar.points", inherit.aes=T)
p
我的代码看起来像这样
$array = Array (
[abc] => Array ( )
[def] => Array ( )
[hij] => Array ( )
[media] => Array (
[video_info] => Array ( )
[video_variants] => Array ( )
[1] => Array ( )
[2] => Array ( )
)
)
我想检查&#34; video_info键是否在数组中可用
我已经尝试过这个功能,但它不起作用
foreach($response->extended_entities->media as $media)
{
stuffs
foreach ($media->video_info->variants as $video)
{
stuffs
}
}
请帮帮我
答案 0 :(得分:1)
尝试这样的事情(递归)
$key = "video_info";
$invoke = findKey($array, $key);
function findKey($array, $key)
{
foreach ($array as $key0 => $value) {
if (is_array($value)) {
if ($key === $key0) {
echo 'hit: key ' . $key . ' is present in the array';
return true;
}
findKey($value, $key); // recursion
} elseif ($key === $key0) {
echo 'hit: key ' . $key . ' is present in the array';
return true;
} else {
return false;
}
}
}
小记:此功能明显快于接受的答案(因子4x)
答案 1 :(得分:0)
这是我使用Recursive Iterator类编写函数来检查数组键的方法...
function isArrayKeyAnywhere( $array, $searchKey )
{
foreach( new RecursiveIteratorIterator( new RecursiveArrayIterator( $array ), RecursiveIteratorIterator::SELF_FIRST ) as $iteratorKey => $iteratorValue )
{
if( $iteratorKey == $searchKey )
{
return true;
}
}
return false;
}
$array = [
'abc'=>[],
'def'=>[],
'hij'=>[
'media'=>[
'video_info'=>[
'video_variants'=>[
[],
[]
]
]
]
]
];
var_dump( isArrayKeyAnywhere( $array, 'video_info' ) ); // true
var_dump( isArrayKeyAnywhere( $array, 'foo_bar' ) ); // false