douao1926 2017-05-10 09:28 采纳率: 0%
浏览 266

将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

  • 写回答

1条回答 默认 最新

  • douwen5690 2017-05-10 10:25
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置