PHP add element in multidimensional array-ThrowExceptions

Exception or error:

How can I add an element to this multidimensional array?

Array
(
    [Items] => Array
        (
            [0] => Array
                (
                    [Item] => 211
                    [Unit] => 11
                    [Quantity] => 2
                    [GST] => True
                )

            [1] => Array
                (
                    [Item] => 210
                    [Unit] => 11
                    [Quantity] => 1
                    [GST] => True
                )

        )

)

PHP:

foreach ($data['Items'] as $Item) {
    array_push($Item, 'User' => 1);
}
How to solve:

You have two problems with your loop.

First, this syntax array_push($Item, 'User' => 1); is wrong, array_push adds a value to the array and the => should only be used inside arrays. Instead of array_push you can use $arr[] = 'your value' and the result will be similar.

Second, for the $Item variable to hold the added value outside the loop you need to pass it by reference, like this:

foreach ($data['Items'] as &$Item) {
    $Item['User'] = 1;
}

Answer:

You didn’t say what you exactly want but simply you can add like this

$array = Array
(
    'Items' => Array
        (
            '0' => Array
                (
                    "Item" => 211,
                    "Unit" => 11,
                    "Quantity" => 2,
                    "GST" => True
                )

        )

);

$array["Items"][0]["new_value"] = "Some Value";

echo "<pre>";
print_r($array);

Answer:

You must access to the array with the [ ], e.g. this code insert a new item with key 2:

$data['Items'][] = array([Item] => 234
                [Unit] => 22
                [Quantity] => 3
                [GST] => False);

Or, if you need to add an element to every Item:

foreach ($data['Items'] as $k)
{
    $k[] = array([Item] => 234
                    [Unit] => 22
                    [Quantity] => 3
                    [GST] => False);
}

Read here for more info: PHP’s Arrays

Answer:

Try that way :

<?php
$prod_id=1;$size="s";$colour="red"; 
$foo["cart"] = array (  
    1 => array (  
        array ('size'=>'S','color'=>'white')  
        ,  
        array ('size'=>'M','color'=>'red')  
    ),  
    2 => array (  
        array ('size'=>'S','color'=>'black')  
        ,  
        array ('size'=>'XL','color'=>'royal')  
    )  
); 
array_push($foo["cart"][$prod_id], array ("quantity" => 1, "size" => $size, "colour" => $colour));   
print_r($foo);
?>

Leave a Reply

Your email address will not be published. Required fields are marked *