user1713385
user1713385

Reputation: 23

accessing array in array data pass from controller to view of codeigniter

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? :(

Upvotes: 1

Views: 2617

Answers (2)

Jordan Arsenault
Jordan Arsenault

Reputation: 7388

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;?>

Upvotes: 0

carlos21
carlos21

Reputation: 485

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); }

Upvotes: 1

Related Questions