php - finding keys in an array that match a pattern

前端 未结 6 593
刺人心
刺人心 2020-12-10 11:13

I have an array that looks like:

 Array ( [2.5] => ABDE [4.8] => Some other value ) 

How would I find any key/value pair where the k

相关标签:
6条回答
  • 2020-12-10 11:42

    you can simply loop through the array and check the keys

    $array = array(...your values...);
    
    foreach($array as $key => $value) {
        if (preg_match($pattern,$key)){
            // it matches
        }
    }
    

    You can wrap it in a function and pass your pattern as parameter

    0 讨论(0)
  • 2020-12-10 11:45

    That are my ways

    $data = ["path"=>"folder","filename"=>"folder/file.txt","required"=>false];
    
    // FIRST WAY
    
    $keys = array_keys($data);
    if (!in_array("path", $keys) && !in_array("filename",$keys) && !in_array("required",$keys)) {
        return myReturn(false, "Dados pendentes");
    }
    
    // SECOND WAY
    
    $keys = implode("," array_keys($data));
    if (!preg_match('/(path)|(filename)|(required)/'), $keys) {
        return myReturn(false, "Dados pendentes");
    }
    
    0 讨论(0)
  • 2020-12-10 11:47

    For future programmers who encounter the same issue. Here is a more complete solution which doesn't use any loops.

        $array = ['2.5'=> 'ABCDE', '2.9'=>'QWERTY'];
        $keys = array_keys($array);
        $matchingKeys = preg_grep('/^2\.+/', $keys);
        $filteredArray = array_intersect_key($array, array_flip($matchingKeys));
        print_r($filteredArray);
    
    0 讨论(0)
  • 2020-12-10 11:49

    I think you need something like this:

    $keys = array_keys($array);
    $result = preg_grep($pattern, $keys);
    

    The result will be a array that holds all the keys that match the regex. The keys can be used to retrieve the corresponding value.

    Have a look at the preg_grep function.

    0 讨论(0)
  • 2020-12-10 11:54

    To get just the part of the array with matching keys you could also write

    $matching_array = array_flip(preg_grep($pattern, array_flip($your_array)));
    

    This might just lead to problems performance-wise, if your array gets too big.

    0 讨论(0)
  • 2020-12-10 12:00

    Old question, but here's what I like to do:

    $array = [ '2.5' => 'ABDE', '4.8' => 'Some other value' ];
    

    preg_grep + array_keys will find all keys

    $keys = preg_grep( '/^2\.\d/i', array_keys( $array ) );
    

    You can add array_intersect_key and array_flip to extract a slice of the array that matches the pattern

    $vals = array_intersect_key( $array, array_flip( preg_grep( '/^2\.\d/i', array_keys( $array ) ) ) );
    
    0 讨论(0)
提交回复
热议问题