首页 > 解决方案 > 将数组转换为对象并打印结果

问题描述

我有这个对象和数组数据:

   stdClass Object
    (
        [meta_title] => title
        [meta_description] => 
        [categories] => Array
            (
                [0] => stdClass Object
                    (
                        [name] => cat title
                    )
    
                [1] => stdClass Object
                    (
                        [name] =>cat title 2
                    )
          
            )
    
        )

在行动中,我需要categories name 使用foreach方法打印。我怎么打印这个?!

编辑:

在我的控制器中,我有:

public function index()
{
    helper('text');
    $data = array(
        'meta_title' => 'title',
        'meta_description' => '',
        'categories' => $this->postModel->getNewsCategories(),      
    );

    return view('blog/index', array( 'categories' => (object)$data));
}

鉴于:

<?php foreach ($categories as $category) : ?>
  <a href="#"><?php echo esc($category->name);?></a>
<?end foreach;?>

但我看到这个错误:

Trying to get property 'name' of non-object

标签: phparraysobject

解决方案


我认为下面的代码会起作用

<?php foreach ($categories->categories as $category) } ?>
  <a href="#"><?php echo esc($category->name);?></a>
<?php end foeach; } ?>

推荐阅读