2012-11-14 106 views
1

我該怎麼寫一個函數來檢查 - 只要有一個值存在在一個嵌套數組中的一個鍵然後返回true如何檢查嵌套數組中鍵的值是否存在?

例如,

$input = array(
    "path" => null, 
    "type" => array (
      "post" => null, 
      "page" => null 
     ), 
    "title" => null, 
    "category" => array(
      "image" => "on" 
    ) 
); 

function validate_array($input = array()) 
{ 

    # Loop the array. 
    foreach($input as $key => $value) 
    { 
     if($value && !is_array($value)) return true; 

     elseif(is_array($value)) 
     { 
      validate_array($value); 
     } 
     elseif($value) 
     { 
      return true; 
     } 
    } 

    # Return the result. 
    return false; 
} 

var_dump(validate_array($input)); // return bool(false) 

它應該返回true因爲嵌套陣列中的一個 - - 有一個值,該值

回答

2
# Loop the array. 
foreach($input as $key => $value) 
{ 
    if($value && !is_array($value)) return true; 

    elseif(is_array($value)) 
    { 
     //--->change this line to this<---- 
     if validate_array($value) return true; 
    } 
    elseif($value) 
    { 
     return true; 
    } 
} 

而且,我不相信你需要那最後elseif

+0

謝謝你的幫助! – laukok

1

經過測試,應該工作。當找到一個值時返回true,否則返回false。

function validate_array($input = array()) 
{ 
    # Loop the array. 
    foreach($input as $key => $value) { 
     if (isset($value)) { 
      if (is_array($value)) { 
       if (validate_array($value)) { 
        return true; 
       } 
      } else { 
       return true; 
      } 
     } 
    } 
    # Return the result. 
    return false; 
}