Search code examples
phparraysarray-push

How to insert an array to an array


I would like to add an array to within an existing array. I am tryin to use array_push which works as long as i dont try to assign a key to the array (if i try to add a key i get a syntax error... :-()

This is my initial array:

$ResultArray = array(
    "TransactionDate" => "$TransactionDate",  
    "tx"=>array(
        "0"=>array(
            "TxIndex" => "$TxIndex", 
            "value" => "$Value",  
            "PaymentConfirmedCount" => "$PaymentConfirmedCount"
        ),
        "1"=>array(
            "TxIndex" => "$TxIndex", 
            "value" => "$Value",  
            "PaymentConfirmedCount" => "$PaymentConfirmedCount"
        )
     ) 
 );

i would then like to add:

$ArrayTOAdd = array(
    "0"=>array(
        "TxIndex" => "$TxIndex", 
        "value" => "$Value",  
        "PaymentConfirmedCount" => 
        "$PaymentConfirmedCount"
    )
);

if I try:

array_push($ResultArray->tx, $ArrayTOAdd); 

BUT this does not work and results in a warning of "array_push() [function.array-push]: First argument should be an array"

if i try this :

array_push($ResultArray, $ArrayTOAdd); 

it just adds the array but not to $ResultArray->tx

Any suggestions would be greatly welcomed!


Solution

  • You have to access the element in the array with $ResultArray["tx"] and not $ResultArray->tx. The second one is for the access to members in a php class. So an

    array_push($ResultArray["tx"], $ArrayTOAdd);
    

    should work.