phparraysmultidimensional-arrayreferencearray-push

How to push data into an array which has already been pushed into another array?


Is there a way where I can insert $dialstack inside of $menustack after putting menustack inside of $mainstack?

The outcome that I want is possible by moving array_push($mainstack, $menustack); to the last line, but I am really looking for a way where I can just insert an array to an existing stack of arrays.

$mainstack = ['applet' => "Flow"];

$menustack = ['applet' => "Menu", 'repeat' => "2"];

$dialstack = [];

$dial1 = ['applet' => "Dial", 'number' => "165465468", 'whisper' => "Yes"];
$dial2 = ['applet' => "Dial", 'number' => "654984", 'whisper' => "No"];
$dial3 = ['applet' => "Dial", 'number' => "398965165", 'whisper' => "Yes"];

array_push($mainstack, $menustack);
array_push($dialstack, $dial1);
array_push($dialstack, $dial2);
array_push($dialstack, $dial3);
array_push($menustack, $dialstack);

Solution

  • You just need to know the index of $menustack inside of $mainstack

    $arrayOne = [];
    $arrayTwo = [];
    $arrayThree = [];
    
    // $arrayOne goes inside of $arrayTwo
    array_push($arrayTwo, $arrayOne);
    
    // $arrayThree goes inside of $arrayTwo[0] which is $arrayOne
    array_push($arrayTwo[0], $arrayThree);
    
    var_dump($arrayTwo);