将Yii2 php stdClass()对象转换为特定类的对象

I have a Array from MySql Query and What I did is convert it to object. But after convert into object Is has become object of stdClass() So I want it to be a object of Theme class.

My Cotroller Code

public function actionIndex()
{
    // $theme = Theme::find()->all();
    $query = "SELECT t.*,COUNT(d.id) AS total_downloads FROM `themes` AS T 
                        LEFT JOIN downloads AS D 
                        ON D.theme_id = T.id GROUP 
                        by t.id ORDER BY total_downloads DESC LIMIT 6";
        $connection=Yii::$app->db;  
        $trends = $connection->createCommand($query);
        $model = $trends->queryAll();


    return $this->render('index',[
                'model'=>$model,
            ]);
}

And View Code Look Like

<?php foreach ($model as $themes): ?>
<?php $theme = (object) $themes; ?>

<?php var_dump($theme) ?>
<div class="col-md-4">

</div>  
<?= $theme->name ?>     

How can I covert $model to a object of class Theme.php

doukaojie8573
doukaojie8573 因为它不像我想的那样工作。
3 年多之前 回复
duanrongpai9556
duanrongpai9556 你能解释为什么你不立刻使​​用Theme课程吗?
3 年多之前 回复
douzhu3367
douzhu3367 计数查询做得很好,计数不是问题。我只想将这个数组模型转换为主题类的Object
3 年多之前 回复

1个回答

I found a Solution here.

 function cast($destination, $sourceObject)
{
    if (is_string($destination)) {
        $destination = new $destination();
    }
    $sourceReflection = new ReflectionObject($sourceObject);
    $destinationReflection = new ReflectionObject($destination);
    $sourceProperties = $sourceReflection->getProperties();
    foreach ($sourceProperties as $sourceProperty) {
        $sourceProperty->setAccessible(true);
        $name = $sourceProperty->getName();
        $value = $sourceProperty->getValue($sourceObject);
        if ($destinationReflection->hasProperty($name)) {
            $propDest = $destinationReflection->getProperty($name);
            $propDest->setAccessible(true);
            $propDest->setValue($destination,$value);
        } else {
            $destination->$name = $value;
        }
    }
    return $destination;

and call function like this

    <?php 
    use yii\helpers\Html;
    $theme_obj = new \common\models\Theme();
    use common\Constant;
 ?>

 <?php foreach ($model as $themes): ?>
    <?php $theme = (object) $themes; ?>
    <?php var_dump(Constant::cast($theme_obj , $theme)) ?>
 <?php endforeach ?>

It works perfectly for me.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐