-1

How to insert new array to a specific position in multi dimensional array below is the code, how it will be done using php

$aExistingArray = Array
    (
[pages] => Array
    (
        [0] => Array
            (
                [name] => page1
                [elements] => Array
                    (
                        [0] => Array
                            (
                                [type] => text
                                [name] => question2
                                [title] => PSTN
                            )

                        [1] => Array
                            (
                                [type] => radiogroup
                                [name] => question3
                                [title] => Are you satisfied to our services
                                [choices] => Array
                                    (
                                        [0] => Array
                                            (
                                                [value] => item1
                                                [text] => yes
                                            )

                                        [1] => Array
                                            (
                                                [value] => item2
                                                [text] => no
                                            )

                                    )

                            )

                    )

            )

    ))

Below is the new array which I want to insert to elements position at 0 position, how it will be done using array technique

$aToBeInserted = Array
    (
[0] => Array
    (
        [type] => text
        [name] => name
        [title] => name
        )

[1] => Array
    (
        [type] => text
        [name] => question1
        [title] => Test
    )

)

codebetter
  • 11
  • 2
  • What array are you trying to insert? You've only provided the original array in your post above. – Blake Ottinger Jan 27 '21 at 14:54
  • Does this answer your question? [How to insert an item at the beginning of an array in PHP?](https://stackoverflow.com/questions/1739706/how-to-insert-an-item-at-the-beginning-of-an-array-in-php) – El_Vanja Jan 27 '21 at 14:54
  • The linked duplicate gives you the mechanism. All you really need to provide are the new element and the exact subarray where you wish to insert. – El_Vanja Jan 27 '21 at 14:55
  • @ El_Vanja new element have been posted please check – codebetter Jan 27 '21 at 14:57
  • @BlakeOttinger Question have been edited, kindly check – codebetter Jan 27 '21 at 15:03

1 Answers1

1

Below is the solution, first find the specific index of array, merge the both arrays and then override with original array.

$elementPostition = $arr['pages'][0]['elements'];
$aMergeArray = array_merge($sTobeInsert,$elementPostition );
$arr['pages'][0]['elements'] = $aMergeArray;
codebetter
  • 11
  • 2