2013-02-04 41 views
0

什麼是寫這些檢查的正確方法。我有一個數組,有些時間值沒有設置,或者它們是空的。現在代碼有點難以閱讀,我可以做些什麼來使它看起來更清晰和可信。或者我正在努力解決這個問題。有什麼建議麼?正確的方式來寫這些檢查?

<?php 

private static function filter_yt_data($yt_api_response = null) 
    { 
     $data  = array(); 
     $api  = json_decode($yt_api_response); 
     $api  = $api->data->items[0]; 



     $data = array(
        'id'   => $api->id, 
        'author'  => e($api->uploader), 
        'label'   => e($api->category), 
        'title'   => e($api->title), 
        'description' => e($api->description), 
        'duration'  => $api->duration, 
        'view_count' => $api->viewCount, 
        'access'  => $api->accessControl->embed, 
        'favorite_count'=> $api->favoriteCount 
        ); 

     if($api->accessControl->comment == 'allowed') 
     { 
      $data['comment_count'] = $api->commentCount; 
     } 
     else 
     { 
      $data['comment_count'] = 0; 
     } 

     if($api->ratingCount) 
     { 
      $data['rating_count'] = $api->ratingCount; 
     } 
     else 
     { 
      $data['rating_count'] = 0; 
     } 

     if($api->accessControl->rate == 'allowed') 
     { 
      $data['like_count'] = $api->likeCount; 
     } 
     else 
     { 
      $data['like_count'] = 0; 
     } 

     if($api->thumbnail->hqDefault) 
     { 
      $data['thumbnail'] = $api->thumbnail->hqDefault; 
     } 
     elseif($api->thumbnail->sqDefault) 
     { 
      $data['thumbnail'] = $api->thumbnail->sqDefault; 

     }else 
     { 
      $data['thumbnail'] = null; 
     } 

     return $data; 
    } 

?> 
+0

這個問題似乎是脫離主題,因爲它屬於[codereview.se] –

回答

5
if($api->accessControl->comment == 'allowed') 
     { 
      $data['comment_count'] = $api->commentCount; 
     } 
     else 
     { 
      $data['comment_count'] = 0; 
     } 

也可能是:

$data['comment_count'] = $api->accessControl->comment == 'allowed' ? $api->commentCount : 0; 

這就是所謂的三元運算符

語法:

$variable = (condition) ? if condition true : else; 

在這種方法你可以[R放置所有if-else語句。

+0

如上所述,三元運算符的優秀用法。 –

1

一種方法是初始化,則默認值做檢查:

$data['comment_count'] = 0; 
    if($api->accessControl->comment == 'allowed'){ 
     $data['comment_count'] = $api->commentCount; 
    } 
    $data['rating_count'] = 0; 
    if($api->ratingCount){ 
     $data['rating_count'] = $api->ratingCount; 
    } 
    $data['like_count'] = 0; 
    if($api->accessControl->rate == 'allowed'){ 
     $data['like_count'] = $api->likeCount; 
    } 
    $data['thumbnail'] = null; 
    if($api->thumbnail->hqDefault){ 
     $data['thumbnail'] = $api->thumbnail->hqDefault; 
    }elseif($api->thumbnail->sqDefault){ 
     $data['thumbnail'] = $api->thumbnail->sqDefault; 
    } 

這些也原始數組中被初始化。

+0

我喜歡那個,謝謝。 – GOD

相關問題