你的问题已经有了答案:
if (isset($heystack[$var1][$var2][$var3]))
{
# do something...
}
如果你不知道你有多少个$var1 ... $varN,你只能动态地做它涉及循环或eval,这取决于你是否需要处理字符串或数字键。这已经被问及回答了:
如果您担心速度,例如如果数组始终相同但您需要经常查询它,请先创建一个具有复合键的索引,以便您更轻松地查询它。这可以通过在递归遍历数组时存储所有键来完成:
class CompoundKeys extends RecursiveIteratorIterator
{
private $keys;
private $separator;
public function __construct($separator, RecursiveIterator $iterator, $mode = RecursiveIteratorIterator::SELF_FIRST, $flags = 0)
{
$this->separator = $separator;
parent::__construct($iterator, $mode, $flags);
}
public function current()
{
$current = parent::current();
if (is_array($current))
{
$current = array_keys($current);
}
return $current;
}
public function key()
{
$depth = $this->getDepth();
$this->keys[$depth] = parent::key();
return implode('.', array_slice($this->keys, 0, $depth+1));
}
}
用法:
$it = new CompoundKeys('.', new RecursiveArrayIterator($array));
$compound = iterator_to_array($it, 1);
isset($compound["$var1.$var2.$var3"]);
或者,这可以通过递归遍历并引用原始数组值来完成:
/**
* create an array of compound array keys aliasing the non-array values
* of the original array.
*
* @param string $separator
* @param array $array
* @return array
*/
function array_compound_key_alias(array &$array, $separator = '.')
{
$index = array();
foreach($array as $key => &$value)
{
if (is_string($key) && FALSE !== strpos($key, $separator))
{
throw new InvalidArgumentException(sprintf('Array contains key ("%s") with separator ("%s").', $key, $separator));
}
if (is_array($value))
{
$subindex = array_compound_key_alias($value, $separator);
foreach($subindex as $subkey => &$subvalue)
{
$index[$key.$separator.$subkey] = &$subvalue;
}
}
else
{
$index[$key] = &$value;
}
}
return $index;
}
用法:
$index = array_compound_key_alias($array);
isset($index["$var1.$var2.$var3"]);