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;
    }

?>
4

2 回答 2

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;

这样,您可以替换所有 if-else 语句。

于 2013-02-04T21:01:51.400 回答
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;
    }

这些也可以在原始数组中初始化。

于 2013-02-04T21:02:33.087 回答