我有一个数组:
<?php
$array = [
'fruits' => [
'apple' => 'value',
'orange' => 'value'
],
'vegetables' => [
'onion' => 'value',
'carrot' => 'value'
];
我还有一个字符串:
$string = 'fruits[orange]';
有什么方法可以检查字符串中指定的 - 数组键 - 是否存在于数组中?
例如:
<?php
if(array_key_exists($string, $array))
{
echo 'Orange exists';
}
最佳答案
试试这个。这里我们使用了 foreach
和 isset
函数。
Note: This solution will also work for more deeper levels Ex:
fruits[orange][x][y]
<?php
ini_set('display_errors', 1);
$array = [
'fruits' => [
'apple' => 'value',
'orange' => 'value'
],
'vegetables' => [
'onion' => 'value',
'carrot' => 'value'
]
];
$string = 'fruits[orange]';
$keys=preg_split("/\[|\]/", $string, -1, PREG_SPLIT_NO_EMPTY);
echo nestedIsset($array,$keys);
function nestedIsset($array,$keys)
{
foreach($keys as $key)
{
if(array_key_exists($key,$array))://checking for a key
$array=$array[$key];
else:
return false;//returning false if any of the key is not set
endif;
}
return true;//returning true as all are set.
}
关于PHP 数组键存在于字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46444379/