1

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 Answers 2

1

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); }
Sign up to request clarification or add additional context in comments.

Comments

0

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 Comment

See updated answer... after your comment - which apparently you've now removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.