1

I need to work out how to do I get the following to work.

I have an array with sub-array

array (
  'session' => '1359964785.85203874781',
  'status' => 'cart',
  'items' => 
  array (
    'id' => '510bca8138fc5d6e38000000',
    'quantity' => '1',
  ),
)

then when I put that array thought my foreach

<?php
       $cart = Shop::get_cart();
       ;
            if($cart != NULL)
            { 
                foreach($cart[0]['items'] as $items)
                {
                    print $items['id'];
                ?>
                <tr>

                </tr>
                <?php
                }   
            }
       ?>

I can't seem to access the sub array for items. What I want to be able to do is call it like

$items["id"];
$items["quantity"];

EDIT

I am getting the data from MongoDB by the following code

public function get_cart()
    {
        $collection = static::db()->redi_shop_orders;
        $cursor = $collection->find(array('session' => $_SESSION["redi-Shop"]));
        if ($cursor->count() > 0)
        {
            $posts = array();
            // iterate through the results
            while( $cursor->hasNext() ) {   
                $posts[] = ($cursor->getNext());
            }
            return $posts;
        }
    }

which when I do a print out returns

Array ( [0] => Array ( [_id] => MongoId Object ( [$id] => 510f8eba38fc5d7d43000000 ) [session] => 1359964785.85203874781 [status] => cart [items] => Array ( [id] => 510bca8138fc5d6e38000000 [quantity] => 1 ) ) )
1
  • 1
    is_array($cart)? isset($cart[0])? isset($cart[0]['items'])? is_array($cart[0]['items'])? - There's some really basic debugging you can do on your own. Commented Feb 4, 2013 at 11:13

2 Answers 2

4

YOu should replace

foreach($cart[0]['items'] as $items)

with

foreach($cart['items'] as $items)
Sign up to request clarification or add additional context in comments.

2 Comments

foreach($cart['items'] as $items)
var_dump($cart) what do you have ?
0
<?php
   $cart = array (
  'session' => '1359964785.85203874781',
  'status' => 'cart',
  'items' => 
  array (
 'id' => '510bca8138fc5d6e38000000',
'quantity' => '1',
 ),
);

        if($cart != NULL)
        { 
            foreach($cart['items'] as $items)
            {
                print $items['id'];
            ?>
            <tr>

            </tr>
            <?php
            }   
        }
   ?>

1 Comment

Could you explain what went wrong and how you fixed it? That way it will be clear very fast to everyone.

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.