我的类中有这个方法,它运行得很好,(有点)。但无论出于何种原因,它都返回NULL。但是,如果我在函数中放入(print_r($keys)),它就会打印出来
RETURN没有传递值。有什么想法吗?
function arrayKeyPath ($searchFor, $arr, $keys=array())
{
if(!empty($arr) && is_array($arr)) {
if(isset($arr[$searchFor])) {
return $keys;
}
foreach($arr as $pKey => $a) {
if(is_array($a)) {
$keys[] = $pKey;
arrayKeyPath($searchFor, $a, $keys);
}
}
}
}
$user['results'][0] = array (
'userId' => '1',
'firstName' => 'John',
'lastName' => 'Doe',
'options' =>
array (
'showNews' => 'on',
'newOptions' => array(
'option1'=> 1,
'option2'=> 2,
'option3'=> 3
),
'connectWithTimeFrame1' => '30',
'defaultMessageTemplate' => '12',
'connectWithTimeFrame' => 90,
),
);
$exists = arrayKeyPath('option1', $user['results'][0]);
var_dump($exists);
联机运行版本https://ideone.com/fnml1S
因此,您基本上要做的是在多维数组中搜索键。如果你只想检查钥匙是否在那里,请考虑以下代码:
// shamelessly copied from http://codeaid.net/php/extract-all-keys-from-a-multidimensional-array
function array_keys_multi(array $array) {
$keys = array();
foreach ($array as $key => $value) {
$keys[] = $key;
if (is_array($value))
$keys = array_merge($keys, array_keys_multi($value));
}
return $keys;
}
// in your case:
// array("results", 0, "userId", "firstName", "lastName", "options", "showNews", "newOptions", "option1", "option2", "option3", "connectWithTimeFrame1", "defaultMessageTemplate", "connectWithTimeFrame");
// call the function
$keys = array_keys_multi($user);
// check if the "option1" can be found in the array
if (in_array("option1", $keys))
echo "Yup, in there.";