2012-02-07 85 views
0

海蘭,PHP動態數組檢查

我有子排列多維數組和這樣的東西:

[21] => Array 
     (
      [80] => 
      [83] => 
      [A4] => Array 
       (
        [80] => 
       ) 

      [85] => 
      [A6] => Array 
       (
        [80] => 
       ) 

      [87] => 
      [88] => 
      [A9] => Array 
       (
        [A0] => Array 
         (
          [80] => 
         ) 

       ) 

      [8B] => 
      [AC] => Array 
       (
        [30] => Array 
         (
          [81] => 
          [82] => 
          [83] => 
          [84] => 
          [85] => 
          [86] => 
          [88] => 
         ) 

       ) 

      [8D] => 
      [8E] => 
      [8F] => 
      [91] => 
      [92] => 
      [93] => 
      [94] => 
      [9B] => 
      [96] => 
      [97] => 
      [9D] => 
     ) 

我想創建一個函數來通一平檢查array_keys_exist

如果水平是0那麼它應該array_keys_exist($array['21']); 如果水平是1那麼應該是array_keys_exist($array['21'][])但問題是我不能使用$array[21][]並且只有ckech 80,80,A0 and 30

這可能嗎?

謝謝

+2

聽起來有點混亂,你怎麼0/1級是什麼意思? – 2012-02-07 10:41:10

+0

如果level是1我想檢查給定的鍵是否存在$ array [21] []鍵(在這種情況下只有:80,80,A0和30') - 通常它會是'array_keys_exist($ array [ 21] [A4])... $ array [21] [A6] ... $ array [21] [A9] ... $ array [21] [AC]' – pufos 2012-02-07 10:45:50

回答

0
function array_key_exists_recursive($key, $array, $levelsToCheck = 0) { 
    if (array_key_exists($key, $array) { 
    return true; 
    } 
    if($levelsToCheck > 0) { 
    foreach($array as $entry) { 
     if(is_array($entry) && 
     array_key_exists_recursive(
      $key, 
      $entry, 
      $levelsToCheck - 1 
     ) 
    ) { 
     return true; 
     } 
    } 
    } 
    return false; 
} 

或者,如果你只是想在一個給定的深度檢查所有的數組:

function array_key_exists_at_depth($key, $array, $depth = 0) { 
    if ($depth <= 0) { 
    return array_key_exists($key, $array); 
    } 
    foreach($array as $entry) { 
    if(is_array($entry) && 
     array_key_exists_at_depth (
      $key, 
      $entry, 
      $depth - 1 
     ) 
    ) { 
     return true; 
    } 
    } 
    return false; 
}