简体   繁体   中英

Array in functions Yii Framework

can someone tell me what is this code doing, As im new to Yii, learning about it.. im not able to understand few things.. Here is the code..

$allmsg = LogMsg::model()->findAll($criteria); // 
    $dataArr = array();
    if (isset($allMsg) && sizeof($allMsg) != 0):
        foreach ($allMsg as $msg) {
            $dataArr[$msg->date][] = array( // array?
                'category' => $msg->category, // what is that 'category' a variable or something else? and $msg->category, is what?
                'time' => $msg->time,
                'date' => $msg->date,
                'user' => $msg->name
            );
        }   endif; 
$this->render('index', array(
            'data' => $dataArr ) //what is that 'data'?
    );

My question is, what is this line of code doing exactly in foreach loop

$dataArr[$msg->date][] = array(
                'category' => $msg->category,

and here is second code... which has something like that..

$allCat = Categories::model()->findAll($criteria);
    $catArr=array();
    if(isset($allCat) && sizeof($allCat)!=0):
        foreach ($allCat as $catModel) {
            $catArr[$catModel->id] =$catModel;
        }
    endif;
    return $catArr;

so what is this line doing in this code in foreach loop, what is different between these two lines in first and second code..

$catArr[$catModel->id] =$catModel;

last thing.. what is it

    public static function getID($category)
{
    $arr = array(
        'ast'=>1, // what are these things? from where are they coming? db?
        'fp'=>5, //
        'per'=>3, 
        'ts'=>6,
        'lg'=>3
    );
    return isset($arr[$category])?$arr[$category]:null;  //Ternary - Condensed if/else statement
}

So as per your first question.

$dataArr[$msg->date][] = array( 'category' => $msg->category,

$allMsg is the active record object which u get through the db query. This object is traversed in a loop and each row is "$msg".

Hence you can access the attributes of the model through the $msg->category. 'category' here is the attribute of the model.

I think, your question is not about Yii. You should read about arrays of PHP first. In the code multidimensional array have been used. It means that the array can contain another array as value.

this is creating multidimensional array.

Your first question

$dataArr[$msg->date][] = array(
                'category' => $msg->category,

will generate output like

[2016-03-04] => Array
        (
            [0] => Array
                (
                    [category] => abc
                )

        )

And your second question

$catArr[$catModel->id] =$catModel;

will genrate output like

array(
     [0] =>1,
    [1] => 2,
    [2] => 3,
)

Not tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM