Array Merge PHP continues to create child / dimensional arrays

I tried to solve this problem for several days. I didn’t go anywhere. On my website there is an opportunity to choose what topics you do at school. The front end works fine, and I can get the result in a table in a column subjects.

The problem arises when adding several objects: it creates a child for each item that I add. This, when several items have been added, leads to something like this:

[
{
    "subject": {
        "level": "hl",
        "subject": "mathematics"
    }
},
[
    {
        "subject": {
            "level": "hl",
            "subject": "french"
        }
    },
    [
        {
            "subject": {
                "level": "hl",
                "subject": "history"
            }
        }
    ]
]
]

As you can see, every time a user adds a topic, a child is created to hold on to all previous topics that have been added. What I'm trying to achieve looks something like this:

[
{
    "subject": {
        "level": "hl",
        "subject": "mathematics"
    }
},
{
    "subject": {
        "level": "hl",
        "subject": "french"
    }
},  
{
    "subject": {
        "level": "hl",
        "subject": "history"
    }
}
]

The PHP code that I use to combine the two arrays is as follows:

    //The user selected subject 
    $input = $request->only(['subject', 'level']);

    //Make a user model
    $user = Auth::user();

    //Format for array
    $add_subject['subject'] = [
        'subject' => $input['subject'],
        'level' => $input['level'],
    ];

    //Get the subjects the user already has from the user model
    $user_subjects = $user->subjects;

    //Make the two arrays
    $array1 = array($add_subject);
    $array2 = array($user_subjects);

    //Merge the two arrays
    $merge = array_merge($array1, $array2);

    //Save the array in database
    $user->subjects = $merge;
    $user->save();

. ?

+4
2

:

$array2 = array($user_subjects);

, $user_subjects , . , array_merge. :

$user_subjects[] = $add_subject;
+3

:

//The user selected subject 
$input = $request->only(['subject', 'level']);

//Make a user model
$user = Auth::user();

// add item to user subjects
$user->subjects[] = [
    'subject' => $input['subject'],
    'level' => $input['level'],
];

//Save the array in database
$user->save();
0

Source: https://habr.com/ru/post/1692842/