我需要遍历一个多维数组并且只检查标题,如果不是以字母开头,如下所示:
Array
(
[0] => Array
(
[letter] =>
[id] => 176
)
[1] => Array
(
[letter] => "
[id] => 175
)
.....etc
所以我需要只检查字母,如果没有以a-zA-z开头,我试过这样做,但仍然有一些缺失,
$notMatch = array();
foreach ($data as $value) {
foreach ($value as $item['title']=>$d) {
if(!preg_match('/^[a-zA-Z]$/',$d)){
$notMatch[]=$d;
}
}
}
答案 0 :(得分:1)
见下面的网址我觉得这对你很有帮助。
<强>更新强>
Using preg_match on a multidimensional array to return key values arrays
试一试
<?php
$data = array(
"abc"=>array(
"label" => "abc",
"value" => "def",
"type" => "ghi",
"desc" => "jkl",
),
"def"=>array(
"label" => "mno",
"value" => "qrs",
"type" => "tuv",
"desc" => "wxyz",
),
);
$matches = array();
$pattern = "/a/i"; //contains an 'a'
//loop through the data
foreach($data as $key=>$value){
//loop through each key under data sub array
foreach($value as $key2=>$value2){
//check for match.
if(preg_match($pattern, $value2)){
//add to matches array.
$matches[$key]=$value;
//match found, so break from foreach
break;
}
}
}
echo '<pre>'.print_r($matches, true).'</pre>';
?>
答案 1 :(得分:1)
我删除了一个foreach循环并更改了preg_match模式,删除了字符串/行的开头和字符串/行锚点的结尾。
我就这样做了:
// I'm assuming your data array looks something like this:
$data = array(array('title'=>'fjsdoijsdiojsd', 'id'=>3),
array('title'=>'oijijsd', 'id'=>5),
array('title'=>'09234032', 'id'=>3));
$notMatch = array();
foreach ($data as $value) {
if(!preg_match('/([a-zA-Z]).*/',$value['title'])){
$notMatch[]=$value['title'];
echo 'notmatch! ' . $value['title'];
}
}
但是,具有更多正则表达式经验的人很可能会为您提供更好的模式。 :)