简短的答案是,如果“第二维”可能在任何地方,您都必须至少隐式循环才能做到。如果必须在第一项中,您只需
is_array($arr[0]);
但是,我能找到的最有效的通用方法是在数组上使用一个foreach循环,每当找到一个命中点时就会短路(至少隐式循环比直接的for()更好):
$ more multi.php<?php$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));$b = array(1 => 'a',2 => 'b');$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));function is_multi($a) { $rv = array_filter($a,'is_array'); if(count($rv)>0) return true; return false;}function is_multi2($a) { foreach ($a as $v) { if (is_array($v)) return true; } return false;}function is_multi3($a) { $c = count($a); for ($i=0;$i<$c;$i++) { if (is_array($a[$i])) return true; } return false;}$iters = 500000;$time = microtime(true);for ($i = 0; $i < $iters; $i++) { is_multi($a); is_multi($b); is_multi($c);}$end = microtime(true);echo "is_multi took ".($end-$time)." seconds in $iters timesn";$time = microtime(true);for ($i = 0; $i < $iters; $i++) { is_multi2($a); is_multi2($b); is_multi2($c);}$end = microtime(true);echo "is_multi2 took ".($end-$time)." seconds in $iters timesn";$time = microtime(true);for ($i = 0; $i < $iters; $i++) { is_multi3($a); is_multi3($b); is_multi3($c);}$end = microtime(true);echo "is_multi3 took ".($end-$time)." seconds in $iters timesn";?>$ php multi.phpis_multi took 7.53565130424 seconds in 500000 timesis_multi2 took 4.56964588165 seconds in 500000 timesis_multi3 took 9.01706600189 seconds in 500000 times
隐式循环,但是一旦找到匹配项我们就无法短路…
$ more multi.php<?php$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));$b = array(1 => 'a',2 => 'b');function is_multi($a) { $rv = array_filter($a,'is_array'); if(count($rv)>0) return true; return false;}var_dump(is_multi($a));var_dump(is_multi($b));?>$ php multi.phpbool(true)bool(false)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)