循环遍历多维数组

时间:2016-10-05 08:44:41

标签: php

我有一个循环遍历多维数组的函数:

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 ...

我知道这没什么大不了的,并且不会影响结果,但为了从中学习: *脚本的哪一部分涉及此错误? *我如何避免这种情况(或者我做错了什么)? 感谢

3 个答案:

答案 0 :(得分:0)

使用for循环而不是while循环,因为您可以首先使用数组的索引

然后,您要检查$date是否存在,您的数组中没有密钥,而以$开头的密钥不是正确的索引;你的第二维指数是&#34; 10:00&#34; ,&#34; 11:00&#34;而不是datehour

答案 1 :(得分:0)

我还会在所有isset($array[$bottom])语句中测试isset($array[$bottom][$field])if

答案 2 :(得分:0)

如果您的多维数组对于每个元素都没有相同的结构,那么您可能需要添加一些isset()函数来测试是否存在具有关联键的数组,然后再对其进行测试if()声明。

相关问题