欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

基础题,通过递归正则匹配数字元素

程序员文章站 2022-05-21 18:57:42
...
digui函数程序功能为通过递归正则匹配数字

如果是数字就保存到新数组中保存,最后返回所有包含数字的元素的数组


$array=array(
"22",
"1234",
array("a",
array("aab","00000","aaa","222000","3333000"),
"aa","999","aaaa"),
"d",
"567",
"33",
"dsf");
$fl_array=array();
function digui($arr)
{
global $fl_array;
foreach($arr as $key=>$value)
{
if (is_array($value))
{
digui($value);
}
}

$fl_array = preg_grep("/\d+/", $arr);

return $fl_array;

}

print_r(digui($array));
?>


回复讨论(解决方案)

$array=array(  "22",  "1234",  array(    "a",    array("aab","00000","aaa","222000","3333000"),    "aa","999","aaaa"),  "d",  "567",  "33",  "dsf");function digui($arr) {   $fl_array = array();  foreach($arr as $key=>$value) {    if(is_array($value)) {      $fl_array = array_merge($fl_array, digui($value));    }  }  $fl_array = array_merge($fl_array, @preg_grep("/\d+/", $arr));     return $fl_array;}print_r(digui($array));
Array
(
[0] => 00000
[1] => 222000
[2] => 3333000
[3] => 999
[4] => 22
[5] => 1234
[6] => 567
[7] => 33
)

$result=array();global $result;function getNum($arr){ 	global $result;	foreach ($arr as $value) {		if(is_array($value)){			getNum($value);		}		if(is_numeric($value)){			array_push($result, $value);		}	}	return $result;}print_r(getNum($array));
这样好像也可以