对多维数组使用preg_match返回键值数组


Using preg_match on a multidimensional array to return key values arrays

我有一个结构如下的数组:

$data = array(
    "abc"=>array(
            "label" => "abc",
            "value" => "def",
            "type" => "ghi",
            "desc" => "jkl",
            ),
    "def"=>array(
            "label" => "mno",
            "value" => "qrs",
            "type" => "tuv",
            "desc" => "wxyz",
            ),
    );

我想在foreach循环中使用preg_match来对$data中包含的数组执行搜索,并返回键值对的嵌套数组。

对于谷歌人来说,这里有更好的代码

$data = <as above>
$pattern = "/whatever/";
$matches = array_filter($data, function($a) use($pattern)  {
    return preg_grep($pattern, $a);
});

类似的东西?

<?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>';
?>

如果你使用的是PHP 5.5,并且在2015年查看这个问题,这可能是一个更简单的答案:

$elements= array_column($array, 1); //Where 1 is the name of the column or the index
$foundElements = preg_grep("/regex/i", $elements);

上面的答案都不适用于我的案例,所以我将把我的解决方案留在这里,也许它对有用

function multidimensionalArrayScan($arr, $pattern, &$result = []) : Array
    {
        foreach ($arr as $key => $value) {
            if (is_array($arr[$key])) {
                self::multidimensionalArrayScan($arr[$key], $pattern, $result);
                continue;
            }
            $match  = preg_match($pattern, $value);
            if (!empty($match))
                $result[$key] = $value;
        }
        return $result;
    }
$data = <as above>
$pattern = "/whatever/";
multidimensionalArrayScan($data, $pattern);
$c=['abccd','123','12qw']; // where u'll search
$a = Array('/a/i', '/'d/i', '/'d+'w/i'); // what is
$b = array_map(function($a,$c){return (preg_match_all($a,$c,$m))? ($m[0][0]) : '';}, $a,$c);
print_r($b);
preg_grep('/needle/iu', array_column($haystack, "columnName", "keyName" ) );

数组$haystack 中列columnName上不区分大小写的unicode grep

preg_match_all返回与具有特定列名的模式匹配的行。

$pattern = "/REDUCTION/i";
$reductions = array_filter($data, function($a) use($pattern)  {
    return preg_match_all($pattern, $a['budget']);
});