Skip to content
Advertisement

convert an array to object and print result

I have this object and array data:

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

in action, I need to print categories name using foreach method. how do can i print this?!

edit:

in my controller i have:

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

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

in view:

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

But i see this error:

Trying to get property 'name' of non-object

Advertisement

Answer

I think code below will work

<?php foreach ($categories->categories as $category) } ?>
  <a href="#"><?php echo esc($category->name);?></a>
<?php end foeach; } ?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement