Array value only returning first character and extra values

Viewed 551

I'm trying to display pizza toppings in a cart. I've stored the pizzas and toppings as a multi-dimensional array, this part is fine, here is an example of 1 item with 2 toppings using print_r()

Array ( [Special Pizza2] => Array ( [id] => 22 [name] => Special Pizza [quantity] => 1 [des] => [top1] => Array ( [id] => 1 [des] => Beef [qty] => 1 ) [top2] => Array ( [id] => 2 [des] => Chicken [qty] => 1 ) ) )

I've searched online and on SOF but am still left scratching my head.

As you'll see in the main code below I've used print_r() on each topping so I could check the arrays for the 2 toppings and to me they seem to display as I'd expect;

Array ( [id] => 1 [des] => Beef [qty] => 1 )

AND

Array ( [id] => 2 [des] => Chicken [qty] => 1 )

Code:

$cart = $_SESSION["cart"];
$c = 0;
foreach($cart as $value)
    {
        if($c==0){
        echo '<div class="crtitm" style="background-color:#e6e6e6;">';
        $c = 1;
    }else{
        echo '<div class="crtitm">';
        $c = 0;
    }

    echo '<b>' .$value[name]. '</b><br>';
//11 because there are 11 toppings
    for ($x = 1; $x <= 11; $x++) {
        $top = "top".$x;
        $pizza = $value[$top];
print_r($pizza);
        foreach($pizza as $return)
        {
                echo $return[des] .'<br>';
        }
    }
    echo $value[des] .'<br>';

    echo '</div>';
}

Now for some reason my code is returning

1
B
1

AND

2
C
1

So I know that this is returning the "id" of the topping then the first char of "des" and then the "qty".

I want my code to just literally just display "Des" +Line-break and then the next topping and so on

for reference, the total output is;

Special Pizza
Array ( [id] => 1 [des] => Beef [qty] => 1 )
1
B
1
Array ( [id] => 2 [des] => Chicken [qty] => 1 )
2
C
1

And the output of print_r($cart) returns this;

Array ( [Special Pizza2] => Array ( [id] => 22 [name] => Special Pizza [quantity] => 1 [des] => [top1] => Array ( [id] => 1 [des] => Beef [qty] => 1 ) [top2] => Array ( [id] => 2 [des] => Chicken [qty] => 1 ) )

Please tell me where I've gone wrong, appreciate all the help to come!

1 Answers

You don't need this loop:

    foreach($pizza as $return)
    {
            echo $return[des] .'<br>';
    }

Here, $pizza is actually a topping array for one topping, and you only want the description from it. However, you're looping over every element, and then trying to deference it as an array -- which it's not. So just replace the above code with this:

echo $pizza['des'];

Note, aways quote array indexes like this: $pizza['des']

Don't do this: $pizza[des]

Related