基础题,通过递归正则匹配数字元素
程序员文章站
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));
?>
(
[0] => 00000
[1] => 222000
[2] => 3333000
[3] => 999
[4] => 22
[5] => 1234
[6] => 567
[7] => 33
)
如果是数字就保存到新数组中保存,最后返回所有包含数字的元素的数组
$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));这样好像也可以
上一篇: MySQL中的字符串模式匹配(1)
推荐阅读