我有一个遍历多维数组的函数:
function in_multiarray($elem, $array, $field)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom][$field] == $elem)
return true;
else
if(is_array($array[$bottom][$field]))
if(in_multiarray($elem, ($array[$bottom][$field])))
return true;
$bottom++;
}
return false;
}
然后,我这样使用它:
$hoursoff = array( array("10:00" => "2016-10-07", "11:00" => "2016-10-07", "12:00" => "2016-10-07"), array("10:00" => "2016-10-08", "11:00" => "2016-10-08") );
if( in_multiarray("$date", $hoursoff, "$hour") ) { /* do it */ } else { /* don't do it */ }
/* $date and $hour come from database request */
这个很好。但是当我检查error_reporting(E_ALL);它把
Notice: Undefined index ...
我知道这没什么大不了的,也不影响结果,但为了从中吸取教训:*这个错误涉及到脚本的哪个部分?我该如何避免这种情况(或者我做错了什么)?由于
如果你的多维数组不是每个元素都有相同的结构,你可能需要添加一些isset()
函数来测试在你在if()
语句中对它进行测试之前,该数组与其关联的键是否存在。
使用for循环而不是while循环,因为您可以先处理数组的索引
然后你检查$date
是否存在,在你的数组中没有键,以$
开始的键不是一个正确的索引;在你的第二维索引是"10:00","11:00",而不是date
或hour
我还将在所有if
语句中测试isset($array[$bottom])
和isset($array[$bottom][$field])
。