2017-06-23 104 views
3

我有一個示例陣列:計數陣列和異常

$array = [ 
    [ 
     FirstClass, 
     SecondClass, 
     ThirdClass, 
    ], 
    [ 
     ThirdClass, 
     MaxClass 
    ], 
    [ 
     FirstClass, 
     ThirdClass 
    ], 
    [ 
     SecondClass, 
     FirstClass, 
    ] 
]; 

我想,以檢查是否存在MaxClass並且另外如果有多於一個的拋出異常。

所以我做的:

foreach ($array as $class) { 
    if (get_class($class) == 'MaxClass') { 
     //different operations 
    } 
} 

爲了檢查我加入:

$count = 0; 
foreach ($array as $class) { 
    if (get_class($class) == 'MaxClass') { 
     if ($count < 2) { 
     //different operations 
     } else { 
      throw new Exception('Too many MaxClass!'); 
     } 
    } 
} 

但也許比使用變量$ count更好的辦法?

第二個問題 - 我應該使用什麼樣的Exception類?也許RuntimeException?

+1

至於最後一點:使用自定義的異常表達這個意思;也許'類ReachedMaxLimitException擴展LogicException {}'。 – deceze

回答

1

我會去這樣的事情有功能的方法:

class ReachedMaxLimitException extends LogicException {} 

$count = array_reduce(
    call_user_func_array('array_merge', $array), // flatten array 
    function ($count, $o) { return $count + ($o instanceof MaxClass); }, 
    0 
); 

if ($count > 1) { 
    raise new ReachedMaxLimitException; 
} 

顯然,從離婚的完整性檢查你的「// different operations」,但這也正是關鍵。

3

您可以使用標誌變量來檢查:嘗試這種解決方案:

$found_max_class=false; 
foreach ($array as $class) { 
    if (get_class($class) == 'MaxClass') { 
     if($found_max_class) 
     { 
      throw new Exception('Too many MaxClass!'); 
     } 
     $found_max_class =true; 
    } 
} 
+0

謝謝。但我正在考慮與array_map關聯的內容 – serese

1
<?php 

$array = [ 
    [ 
     "FirstClass", 
     "SecondClass", 
     "ThirdClass", 
    ], 
    [ 
     "ThirdClass", 
     "MaxClass" 
    ], 
    [ 
     "FirstClass", 
     "ThirdClass" 
    ], 
    [ 
     "SecondClass", 
     "FirstClass", 
     "MaxClass" 
    ] 
]; 

$countValues = array_count_values(array_reduce($array, 'array_merge', array())); 

var_dump($countValues["MaxClass"]); 

if($countValues["MaxClass"] > 1) { 
    throw new Exception('Too many MaxClass!'); 
} 

看到這裏的例子:http://sandbox.onlinephpfunctions.com/code/9a27d9388b93c4ac4903891517dc8ad531f04a94

1
$restrictions = [MaxClass::class => ['max' => 1, 'found' => 0]]; 

foreach($array as $subArray) { 
    foreach($subArray as $element) { 
     $className = get_class($element); 

     if (isset($restrictions[$className]) { 
      if ($restrictions[$className]['found'] >= $restrictions[$className]['max']) { 
       // throw your exception 
      } 

      $restrictions[$className]['found'] += 1; 
     } 

     // code 
    } 
}