Home > Backend Development > PHP Tutorial > 如何判断一个多维数组里面的值是否都为空?

如何判断一个多维数组里面的值是否都为空?

WBOY
Release: 2016-06-23 13:54:17
Original
1463 people have browsed it

比如这样两个个数组  $arr 认为是空的,$brr 认为是有值的。

$arr=array(0=>'', 1=>array(0=>'' ,1=>array(0=>'') ));$brr=array(0=>'', 1=>array(0=>'' ,1=>array(0=>'1') ));
Copy after login


回复讨论(解决方案)

可以这样

$arr = array(0=>'', 1=>array(0=>'' ,1=>array(0=>'') ));var_dump(preg_replace('/[",\[\]]/', '', json_encode($arr)));
Copy after login
Copy after login
string(0) ""
显然对于 $brr 会是 string(1) "1"

可以这样

$arr = array(0=>'', 1=>array(0=>'' ,1=>array(0=>'') ));var_dump(preg_replace('/[",\[\]]/', '', json_encode($arr)));
Copy after login
Copy after login
string(0) ""
显然对于 $brr 会是 string(1) "1"


这样如果数组很大的话会影响效率?或者可以递归判断是否有值吗?

可能这样要好些

$arr = array(0=>'', 1=>array('a'=>'' ,1=>array(0=>'') ));var_dump(preg_replace('/"\w+":|[",{}\[\]]/', '', json_encode($arr)));
Copy after login

那就怪了,我只执行了两个函数
肯定要比递归要快的多

递归要这样写

$arr = array(0=>'', 1=>array('a'=>'' ,1=>array(0=>'') ));var_dump(foo($arr));function foo($ar) {  if(empty($ar)) return true;  if(is_array($ar)) {    foreach($ar as $v) {      if(! foo($v)) return  false;    }    return true;  }  return flase;}
Copy after login

递归要这样写

$arr = array(0=>'', 1=>array('a'=>'' ,1=>array(0=>'') ));var_dump(foo($arr));function foo($ar) {  if(empty($ar)) return true;  if(is_array($ar)) {    foreach($ar as $v) {      if(! foo($v)) return  false;    }  }  return flase;}
Copy after login


多谢版主!!

$arr=array(0=>'',1=>array(0=>'',1=>array(0=>'')));$brr=array(0=>'',1=>array(0=>'',1=>array(0=>'1')));echo test($arr).'<br>';echo test($brr);function test(&$array){	static $r = 0;	if(!is_array($array)){		if(empty($array)){			$r=0;		}else{			$r=1;		}	}	foreach ($array as $key => $value) {		if (is_array($value)) {			test($array[$key]);		} else {			if(empty($value)){				$r=0;			}else{				$r=1;			}		}	}	return $r;}
Copy after login

结果:
0
1

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template