1
votes

I have this following code in my controller. I want to print the data i have my array.. should it be double forloop or foreach?

CONTROLLER:

public function index()
{
    $in_cart = array();

    if (!isset($_SESSION['cartProducts'])){
        $in_cart['list'] = "No Products";
    }
    else{
        foreach ($_SESSION['cartProducts'] as $key => $value) {
            $in_cart[$key] = $this->shopmod->get_one_data($key);

        }
        $cart['list'] = $in_cart;

    }


    $this->load->vars($cart);
    $data['cart'] = $this->load->view('shop/cart', '',  TRUE);
    $this->load->view('layout/default', $data);
}

VIEW:

<?php if(is_array($list)): ?>
        <?php foreach($list as  $row):?>
            <tr>
                <td><?=$row->name?></td>
            </tr>

        <?php endforeach ?>
    <?php endif;?>

but i have this following error: A PHP Error was encountered Severity: Notice Message: Trying to get property of non-object Filename: shop/cart.php Line Number: 18

anyhelp guys? :(

2

2 Answers

0
votes

PHP is telling you exactly what is wrong.

You are trying to access the name property of the $row array when the -> syntax is specifically reserved for objects.

To access array values, you use square brackets and keys: <?=$row['name']?>

Helpful hint to understand - What you're doing is quasi-equivalent to: 7->name, insofar as the left value (7) has no idea how to use the arrow syntax. It's reserved for when the left value is an object. Not an integer, or in your case, an array.

Update after your comment:

You would get at the data like this:

<? foreach($row['list'] as $r):?>
<tr>
    <td><?=$r[0]->name;?></td>
</tr>
<? endforeach;?>
1
votes

I see you are using Code igniter (nice!)

I would do the following to ensure the $key is taking 'name'

public function index() { foreach ($_SESSION['cartProducts'] as $key => $value) { echo $key; } }

Then

public function index() { $in_cart = array();

if (!isset($_SESSION['cartProducts'])){
    $in_cart['list'] = "No Products";
}
else{
    foreach ($_SESSION['cartProducts'] as $key => $value) {
        $in_cart[$key] = $this->shopmod->get_one_data($key);

    }
}


$this->load->vars($cart);
$data['cart'] = $this->load->view('shop/cart', '',  TRUE);
$data['list'] = $in_cart;
$this->load->view('layout/default', $data); }