1

I want something like this in my template file:

<ul>
<?foreach($friends as $var):?>

        <li>
            <?=$var->name?>
        </li>

<?endforeach ?>
</ul>

I use this in my model.php:

$data = array('friends' => array(
    array('name' => 'testname'),
    array('name' => 'testname2')
));

// missing code here ?

extract($data, EXTR_SKIP);
include('template_file.html');

How can I use $var->name to access 'name' as an object in my template file?

$data = array() is set.

Update:

Its because, I dont want to use <?=$var['name']?> in my template.

Stefan
  • 305
  • 2
  • 10

3 Answers3

0
<ul>
<?
foreach($data as $eachData)
{
 foreach($eachData as $var):?>
  {

        <li>
            <?php echo $var->name?>
        </li>

<?php 
  }
} ?>
</ul>
Aris
  • 4,643
  • 1
  • 41
  • 38
0

$var->name : this is way to get the valus in object.

In arrays to get values use it like this : $var['name']

To convert arrays to object refer this : How to convert an array to object in PHP?

Community
  • 1
  • 1
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
0

Considering this:

$data = array('friends' => array(
    array('name' => 'testname'),
    array('name' => 'testname2')
));

<?foreach($data['friends'] as $var):?>
    <li>
        <!-- $var will be testname2 -->
        <?=$var; ?>
    </li>
<?endforeach ?>

<?foreach($data['friends'] as $key => $var):?>
    <li>
        <!-- $var will be testname2, $key will be "name" -->
        <?=$var; ?>
    </li>
<?endforeach ?>

You should overthink your naming of your array keys. There must be a new key for every value or you will overwrite the previous setted value.

Tobias Golbs
  • 4,586
  • 3
  • 28
  • 49