2017-02-25 31 views
0

工作,我有這樣的用正則表達式匹配數組鍵沒有在PHP

Array (
    [test.0.male_min_months] => Array (
     [0] => The test.0.male_min_months field has a duplicate value. 
    ) 
    [test.42.male_min_months] => Array (
     [0] => The test.42.male_min_months field has a duplicate value. 
    ) 
    [name] => Array (
     [0] => The name field is required. 
    ) 
    [unit_id] => Array (
     [0] => The unit id field is required. 
    ) 
) 

,並檢查在數組鍵的功能陣列

function preg_array_key_exists($pattern, $array) { 
    $keys = array_keys($array); 
    return $array[preg_grep($pattern,$keys)[0]]; 
} 

其爲preg_array_key_exists('/(test.0.male)/',$my_array);

但工作不工作preg_array_key_exists('/(test.42.male)/',$my_array);

+0

隨意downvote,但請解釋。 –

+0

你見過:http://php.net/manual/en/function.preg-grep.php#111673? – Rizier123

回答

0

我將解釋爲什麼/代碼失敗的地方提供解決方案。

當您在自定義函數中調用array_keys()時,每個鍵都會變成帶有索引(自動遞增)鍵的值。

當您撥打preg_grep($pattern,$keys)時,它會創建一個匹配數組並保留數字鍵。特別爲你的情況,"test.42.male_min_months"有一個關鍵1

這意味着return $array[preg_grep($pattern,$keys)[0]]只有在您的模式要求$my_array中的第一個子數組的密鑰時纔會成功。

要更正您現有的功能,使用方法:

current(preg_grep($pattern,$keys)); 

這會子陣,你的鑰匙圖案匹配返回的第一個值。

代碼(Demo與var_export來解釋這個問題):

<?php 
$my_array=array(
    "test.0.male_min_months"=>array(
     0=>"The test.0.male_min_months field has a duplicate value." 
    ), 
    "test.42.male_min_months"=>array(
     0=>"The test.42.male_min_months field has a duplicate value.", 
    ), 
    "name"=>array(
     0=>"The name field is d." 
    ), 
    "unit_id"=>array(
     0=>"The unit id field is d." 
    ) 
); 

function preg_array_key_exists($pattern,$array){ 
    $keys = array_keys($array); // create new indexed array holding each key as a value 
    return $array[current(preg_grep($pattern,$keys))]; 
} 

$pattern="/(test.42.male)/"; // your regex pattern (which doesn't fail you) 
// $pattern="/(test\.42\.male)/"; // escape the literal dots, as a matter of good practice  
$output=preg_array_key_exists($pattern,$my_array); 

附:由於良好的習慣做法,在你的正則表達式使用文字時的點,他們逃脫這樣\.

輸出是:

array (
    0 => 'The test.42.male_min_months field has a duplicate value.', 
) 
+0

@ detective404如果我的答案能夠充分解決您的問題,請給它一個綠色的勾號,以便將您的問題從未回答的問題列表中刪除,以便將來的讀者不會浪費時間解決已解決的問題。如果還是不對,請告訴我。 – mickmackusa