2

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);
}
The Codesee
  • 3,714
  • 5
  • 38
  • 78
Rushabh Shah
  • 49
  • 1
  • 1
  • 3
  • 1
    Forget about `array_push()` and learn how to [access and modify array elements using the square brackets syntax](http://php.net/manual/en/language.types.array.php#language.types.array.syntax.accessing). – axiac Jan 19 '18 at 09:31

4 Answers4

4

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;
}
Claudio
  • 5,078
  • 1
  • 22
  • 33
1

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);
TarangP
  • 2,711
  • 5
  • 20
  • 41
1

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

user2342558
  • 5,567
  • 5
  • 33
  • 54
0

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);
?>
Nims Patel
  • 1,048
  • 9
  • 19